id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
20,400
connect.py
devsnd_cherrymusic/cherrymusicserver/database/connect.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # CherryMusic - a standalone music server # Copyright (c) 2012 - 2016 Tom Wallroth & Tilman Boerner # # Project page: # http://fomori.org/cherrymusic/ # Sources on github: # http://github.com/devsnd/cherrymusic/ # # CherryMusic is based on # jPlayer (GPL/MIT license) http://www.jplayer.org/ # CherryPy (BSD license) http://www.cherrypy.org/ # # licensed under GNU GPL version 3 (or later) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # ''' Connect to databases. ''' # from abc import ABCMeta, abstractmethod # don't, for py2 compatibility import cherrymusicserver.service as service # class AbstractConnector(metaclass=ABCMeta): class AbstractConnector(object): '''Provide database connections by name. Override :meth:`connection` and :meth:`dbname` to subclass. ''' def __repr__(self): return '{0} [{1}]'.format(self.__class__.__name__, hex(id(self))) # @abstractmethod def connection(self, dbname): '''Return a connection object to talk to a database.''' raise NotImplementedError('abstract method') # @abstractmethod def dblocation(self, basename): '''Return the internal handle used for the database with ``basename``.''' raise NotImplementedError('abstract method') def bound(self, dbname): '''Return a :class:`BoundConnector` bound to the database with ``dbname``.''' return BoundConnector(dbname, self) @service.user(baseconnector='dbconnector') class BoundConnector(object): '''Provide connections to a specific database name.''' def __init__(self, dbname, overrideconnector=None): self.name = dbname if overrideconnector is not None: self.baseconnector = overrideconnector def __repr__(self): return '{cls}({0!r}, {1})'.format( self.name, repr(self.baseconnector), cls=self.__class__.__name__) @property def dblocation(self): '''Return the internal handle used for the bound database.''' return self.baseconnector.dblocation(self.name) def connection(self): '''Return a connection object to talk to the bound database.''' return self.baseconnector.connection(self.name) def execute(self, query, params=()): '''Connect to the bound database and execute a query; then return the cursor object used.''' cursor = self.connection().cursor() cursor.execute(query, params) return cursor
3,105
Python
.py
77
35.87013
85
0.699403
devsnd/cherrymusic
1,032
187
111
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,401
sql.py
devsnd_cherrymusic/cherrymusicserver/database/sql.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # CherryMusic - a standalone music server # Copyright (c) 2012 - 2016 Tom Wallroth & Tilman Boerner # # Project page: # http://fomori.org/cherrymusic/ # Sources on github: # http://github.com/devsnd/cherrymusic/ # # CherryMusic is based on # jPlayer (GPL/MIT license) http://www.jplayer.org/ # CherryPy (BSD license) http://www.cherrypy.org/ # # licensed under GNU GPL version 3 (or later) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # '''SQL Database handling.''' import os.path import sqlite3 import tempfile import threading from cherrymusicserver import log from cherrymusicserver.database.connect import AbstractConnector, BoundConnector class SQLiteConnector(AbstractConnector): '''Connector for SQLite3 databases. By specification of the python sqlite3 module, sharing connections is to be considered NOT THREADSAFE. datadir: str Base directories of database files. extension: str (optional) Extension to append to database filenames. connargs: dict (optional) Dictionary with keyword args to pass on to sqlite3.Connection. ''' def __init__(self, datadir='', extension='', connargs={}): self.datadir = datadir self.extension = extension self.connargs = connargs def connection(self, dbname): return sqlite3.connect(self.dblocation(dbname), **self.connargs) def dblocation(self, basename): if self.extension: basename = os.path.extsep.join((basename, self.extension)) return os.path.join(self.datadir, basename) class Updater(object): '''Handle the versioning needs of a single database. name : str The name of the database to manage. dbdef : dict The corresponding definition. connector : :class:`cherrymusicserver.database.connect.AbstractConnector` To connect to the database. ''' _metatable = { 'create.sql': """CREATE TABLE IF NOT EXISTS _meta_version( version TEXT, _created INTEGER NOT NULL DEFAULT (datetime('now')) );""", 'drop.sql': """DROP TABLE IF EXISTS _meta_version;""" } _classlock = threading.RLock() _dblockers = {} def __init__(self, name, dbdef): assert name and dbdef self.name = name self.desc = dbdef self.db = BoundConnector(self.name) with self: self._init_meta() def __del__(self): self._unlock() def __repr__(self): return 'updater({0!r}, {1} -> {2})'.format( self.name, self._version, self._target, ) def __enter__(self): self._lock() return self def __exit__(self, exctype, exception, traceback): self._unlock() @property def _islocked(self): name, lockers = self.name, self._dblockers with self._classlock: return name in lockers and lockers[name] is self def _lock(self): name, lockers = self.name, self._dblockers with self._classlock: assert lockers.get(name, self) is self, ( name + ': is locked by another updater') lockers[name] = self def _unlock(self): with self._classlock: if self._islocked: del self._dblockers[self.name] @property def needed(self): """ ``True`` if the database is unversioned or if its version is less then the maximum defined. """ self._validate_locked() version, target = self._version, self._target log.d('%s update check: version=[%s] target=[%s]', self.name, version, target) return version is None or version < target @property def requires_consent(self): """`True` if any missing updates require user consent.""" self._validate_locked() for version in self._updates_due: if 'prompt' in self.desc[version]: return True return False @property def prompts(self): """ Return an iterable of string prompts for updates that require user consent. """ self._validate_locked() for version in self._updates_due: if 'prompt' in self.desc[version]: yield self.desc[version]['prompt'] def run(self): """Update database schema to the highest possible version.""" self._validate_locked() log.i('%r: updating database schema', self.name) log.d('from version %r to %r', self._version, self._target) if None is self._version: self._init_with_version(self._target) else: for version in self._updates_due: self._update_to_version(version) def reset(self): """Delete all content from the database along with supporting structures.""" self._validate_locked() version = self._version log.i('%s: resetting database', self.name) log.d('version: %s', version) if None is version: log.d('nothing to reset.') return with self.db.connection() as cxn: cxn.executescript(self.desc[version]['drop.sql']) cxn.executescript(self._metatable['drop.sql']) cxn.executescript(self._metatable['create.sql']) self._setversion(None, cxn) cxn.close() def _validate_locked(self): assert self._islocked, 'must be called in updater context (use "with")' @property def _version(self): try: return self.__version except AttributeError: maxv = self.db.execute('SELECT MAX(version) FROM _meta_version').fetchone() maxv = maxv and maxv[0] self.__version = maxv if maxv is None else str(maxv) return self.__version def _setversion(self, value, conn=None): del self.__version conn = conn or self.db.connection log.d('{0}: set version to {1}'.format(self.name, value)) conn.execute('INSERT INTO _meta_version(version) VALUES (?)', (value,)) @property def _target(self): return max(self.desc) @property def _updates_due(self): if None is self._version: return () versions = sorted(self.desc) start = versions.index(self._version) + 1 return versions[start:] def _init_meta(self): content = self.db.execute('SELECT type, name FROM sqlite_master;').fetchall() content = [(t, n) for t, n in content if n != '_meta_version' and not n.startswith('sqlite')] with self.db.connection() as cxn: cxn.isolation_level = "EXCLUSIVE" cxn.executescript(self._metatable['create.sql']) if content and self._version is None: log.d('%s: unversioned content found: %r', self.name, content) self._setversion(0, cxn) cxn.isolation_level = '' cxn.close() def _init_with_version(self, vnum): log.d('initializing database %r to version %s', self.name, vnum) cxn = self.db.connection() cxn.isolation_level = None # autocommit self._runscript(vnum, 'create.sql', cxn) self._run_afterscript_if_exists(vnum, cxn) self._setversion(vnum, cxn) cxn.isolation_level = '' cxn.close() def _update_to_version(self, vnum): log.d('updating database %r to version %d', self.name, vnum) cxn = self.db.connection() cxn.isolation_level = None # autocommit self._runscript(vnum, 'update.sql', cxn) self._run_afterscript_if_exists(vnum, cxn) self._setversion(vnum, cxn) cxn.isolation_level = '' cxn.close() def _run_afterscript_if_exists(self, vnum, conn): try: self._runscript(vnum, 'after.sql', conn) except KeyError: pass def _runscript(self, version, name, cxn): try: cxn.executescript(self.desc[version][name]) except sqlite3.OperationalError: # update scripts are tested, so the problem's seems to be sqlite # itself log.x(_('Exception while updating database schema.')) log.e(_('Database error. This is probably due to your version of' ' sqlite being too old. Try updating sqlite3 and' ' updating python. If the problem persists, you will need' ' to delete the database at ' + self.db.dblocation)) import sys sys.exit(1) class TmpConnector(AbstractConnector): """Special SQLite Connector that uses its own temporary directory. As with the sqlite3 module in general, sharing connections is NOT THREADSAFE. """ def __init__(self): self.testdirname = tempfile.mkdtemp(suffix=self.__class__.__name__) def __del__(self): import shutil shutil.rmtree(self.testdirname, ignore_errors=True) def connection(self, dbname): return sqlite3.connect(self.dblocation(dbname)) def dblocation(self, basename): return os.path.join(self.testdirname, basename) class MemConnector(AbstractConnector): # NOT threadsafe """Special SQLite3 Connector that reuses THE SAME memory connection for each dbname. This connection is NOT CLOSABLE by normal means. Therefore, this class is NOT THREADSAFE. """ def __init__(self): self.connections = {} self.Connection = type( self.__class__.__name__ + '.Connection', (sqlite3.Connection,), {'close': self.__disconnect}) def __del__(self): self.__disconnect(seriously=True) def __repr__(self): return '{name} [{id}]'.format( name=self.__class__.__name__, id=hex(id(self)) ) def connection(self, dbname): return self.__connect(dbname) def dblocation(self, _): return ':memory:' def __connect(self, dbname): try: return self.connections[dbname] except KeyError: cxn = sqlite3.connect(':memory:', factory=self.Connection) return self.connections.setdefault(dbname, cxn) def __disconnect(self, seriously=False): if seriously: connections = dict(self.connections) self.connections.clear() for cxn in connections.values(): super(cxn.__class__, cxn).close()
11,174
Python
.py
283
31.137809
101
0.619996
devsnd/cherrymusic
1,032
187
111
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,402
__init__.py
devsnd_cherrymusic/cherrymusicserver/database/__init__.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # CherryMusic - a standalone music server # Copyright (c) 2012 - 2016 Tom Wallroth & Tilman Boerner # # Project page: # http://fomori.org/cherrymusic/ # Sources on github: # http://github.com/devsnd/cherrymusic/ # # CherryMusic is based on # jPlayer (GPL/MIT license) http://www.jplayer.org/ # CherryPy (BSD license) http://www.cherrypy.org/ # # licensed under GNU GPL version 3 (or later) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # """CherryMusic database definition, versioning and control. To support schema changes that are not backward-compatible, databases can be versioned. """ import itertools from cherrymusicserver import log from cherrymusicserver.database import defs from cherrymusicserver.database import sql def require(dbname, version): """ Raise an AssertionError if the database does not exist or has the wrong version. """ if not dbname: raise ValueError('dbname must not be empty or None') isversion = MultiUpdater.checkversion(dbname) assert isversion == version, ( '{0!r}: bad version: {1!r} (want: {2!r})'.format( dbname, isversion, version)) def ensure_current_version(dbname=None, autoconsent=False, consentcallback=None): '''Make sure all defined databases exist and are up to date. Will connect to all these databases and try to update their layout, if necessary, possibly asking the user for consent. dbname : str When given, only make sure of the database with that name. autoconsent : bool When ``True``, don't ask for consent, ever. consentcallback: callable Called when an update requires user consent; if the return value does not evaluate to ``True``, abort don't run any updates and return ``False``. If no callback is given or autoconsent == True, the value of autoconsent will be used to decide if the update should run. Returns : bool ``True`` if requirements are met. ''' if autoconsent or consentcallback is None: consentcallback = lambda _: autoconsent with MultiUpdater(dbname) as update: if update.needed: if update.requires_consent and not consentcallback(update.prompts): return False log.w("Database schema update; don't turn off the program!") update.run() log.i('Database schema update complete.') return True def resetdb(dbname): '''Delete all content and defined data structures from a database. Raises: ValueError : If dbname is ``None`` or empty, or not a defined database name. ''' if not dbname: raise ValueError('dbname must not be empty or None') with MultiUpdater(dbname) as updater: updater.reset() class MultiUpdater(object): '''Manage the state of multiple databases at once. defs : dict Definitions of all databases to manage. connector : :class:`.connect.AbstractConnector` For connecting to the databases. ''' def __init__(self, dbname=None): if dbname is None: dbdefs = defs.getall() self.updaters = tuple(sql.Updater(k, dbdefs[k]) for k in dbdefs) else: self.updaters = (sql.Updater(dbname, defs.get(dbname)),) def __iter__(self): return iter(self.updaters) def __enter__(self): for updater in self: updater._lock() return self def __exit__(self, exctype, exception, traceback): for updater in self: updater._unlock() @property def needed(self): """``True`` if any database needs updating. See :meth:`.sql.Updater.needed`. """ for updater in self: if updater.needed: return True return False @property def requires_consent(self): """``True`` if any database update needs user consent. See :meth:`.sql.Updater.requires_consent`. """ for updater in self: if updater.requires_consent: return True return False @property def prompts(self): """An iterable of string prompts for updates that require consent.""" return itertools.chain(*(updater.prompts for updater in self)) def run(self): """Update all databases with out of date versions. See :meth:`.sql.Updater.run`. """ for updater in self: if updater.needed: updater.run() def reset(self): """Delete content and data structures of all included databases. See :meth:`.sql.Updater.reset`. """ for updater in self: updater.reset() @classmethod def checkversion(self, dbname): """Return the effective version of a database.""" with sql.Updater(dbname, defs.get(dbname)) as updater: return updater._version
5,572
Python
.py
147
31.435374
81
0.665555
devsnd/cherrymusic
1,032
187
111
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,403
__init__.py
devsnd_cherrymusic/cherrymusicserver/database/defs/__init__.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os _PACKAGEDIR = os.path.dirname(__file__) cache = {} def get(dbname): """The database definition as a ``dict``. Raises : ValueError : if there is no definition for that name """ try: return cache[dbname] except KeyError: dbdef = _loaddef(dbname) return cache.setdefault(dbname, dbdef) def getall(): all = {} for name in _listnames(_PACKAGEDIR): all[name] = get(name) return all def _loaddef(dbname): defdir = os.path.join(_PACKAGEDIR, dbname) if not os.path.isdir(defdir): raise ValueError("{0}: database not defined".format(defdir)) dbdef = dict( (vnum, _loadversion(defdir, vnum)) for vnum in _listnames(defdir)) return dbdef def _loadversion(defdir, version): versiondef = {} versiondir = os.path.join(defdir, version) for name in _listnames(versiondir): fname = os.path.join(versiondir, name) with open(fname) as f: versiondef[name] = f.read() return versiondef def _listnames(path): return (name for name in os.listdir(path) if not name.startswith('__'))
1,180
Python
.py
37
26.432432
75
0.646903
devsnd/cherrymusic
1,032
187
111
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,404
mustache-0.7.0.js
devsnd_cherrymusic/res/js/ext/mustache-0.7.0.js
/*! * mustache.js - Logic-less {{mustache}} templates with JavaScript * http://github.com/janl/mustache.js */ /*global define: false*/ var Mustache; (function (exports) { if (typeof module !== "undefined" && module.exports) { module.exports = exports; // CommonJS } else if (typeof define === "function") { define(exports); // AMD } else { Mustache = exports; // <script> } }((function () { var exports = {}; exports.name = "mustache.js"; exports.version = "0.7.0"; exports.tags = ["{{", "}}"]; exports.Scanner = Scanner; exports.Context = Context; exports.Writer = Writer; var whiteRe = /\s*/; var spaceRe = /\s+/; var nonSpaceRe = /\S/; var eqRe = /\s*=/; var curlyRe = /\s*\}/; var tagRe = /#|\^|\/|>|\{|&|=|!/; // Workaround for https://issues.apache.org/jira/browse/COUCHDB-577 // See https://github.com/janl/mustache.js/issues/189 function testRe(re, string) { return RegExp.prototype.test.call(re, string); } function isWhitespace(string) { return !testRe(nonSpaceRe, string); } var isArray = Array.isArray || function (obj) { return Object.prototype.toString.call(obj) === "[object Array]"; }; function escapeRe(string) { return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); } var entityMap = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': '&quot;', "'": '&#39;', "/": '&#x2F;' }; function escapeHtml(string) { return String(string).replace(/[&<>"'\/]/g, function (s) { return entityMap[s]; }); } // Export the escaping function so that the user may override it. // See https://github.com/janl/mustache.js/issues/244 exports.escape = escapeHtml; function Scanner(string) { this.string = string; this.tail = string; this.pos = 0; } /** * Returns `true` if the tail is empty (end of string). */ Scanner.prototype.eos = function () { return this.tail === ""; }; /** * Tries to match the given regular expression at the current position. * Returns the matched text if it can match, the empty string otherwise. */ Scanner.prototype.scan = function (re) { var match = this.tail.match(re); if (match && match.index === 0) { this.tail = this.tail.substring(match[0].length); this.pos += match[0].length; return match[0]; } return ""; }; /** * Skips all text until the given regular expression can be matched. Returns * the skipped string, which is the entire tail if no match can be made. */ Scanner.prototype.scanUntil = function (re) { var match, pos = this.tail.search(re); switch (pos) { case -1: match = this.tail; this.pos += this.tail.length; this.tail = ""; break; case 0: match = ""; break; default: match = this.tail.substring(0, pos); this.tail = this.tail.substring(pos); this.pos += pos; } return match; }; function Context(view, parent) { this.view = view; this.parent = parent; this.clearCache(); } Context.make = function (view) { return (view instanceof Context) ? view : new Context(view); }; Context.prototype.clearCache = function () { this._cache = {}; }; Context.prototype.push = function (view) { return new Context(view, this); }; Context.prototype.lookup = function (name) { var value = this._cache[name]; if (!value) { if (name === ".") { value = this.view; } else { var context = this; while (context) { if (name.indexOf(".") > 0) { var names = name.split("."), i = 0; value = context.view; while (value && i < names.length) { value = value[names[i++]]; } } else { value = context.view[name]; } if (value != null) { break; } context = context.parent; } } this._cache[name] = value; } if (typeof value === "function") { value = value.call(this.view); } return value; }; function Writer() { this.clearCache(); } Writer.prototype.clearCache = function () { this._cache = {}; this._partialCache = {}; }; Writer.prototype.compile = function (template, tags) { return this._compile(this._cache, template, template, tags); }; Writer.prototype.compilePartial = function (name, template, tags) { return this._compile(this._partialCache, name, template, tags); }; Writer.prototype.render = function (template, view, partials) { return this.compile(template)(view, partials); }; Writer.prototype._compile = function (cache, key, template, tags) { if (!cache[key]) { var tokens = exports.parse(template, tags); var fn = compileTokens(tokens); var self = this; cache[key] = function (view, partials) { if (partials) { if (typeof partials === "function") { self._loadPartial = partials; } else { for (var name in partials) { self.compilePartial(name, partials[name]); } } } return fn(self, Context.make(view), template); }; } return cache[key]; }; Writer.prototype._section = function (name, context, text, callback) { var value = context.lookup(name); switch (typeof value) { case "object": if (isArray(value)) { var buffer = ""; for (var i = 0, len = value.length; i < len; ++i) { buffer += callback(this, context.push(value[i])); } return buffer; } return value ? callback(this, context.push(value)) : ""; case "function": var self = this; var scopedRender = function (template) { return self.render(template, context); }; return value.call(context.view, text, scopedRender) || ""; default: if (value) { return callback(this, context); } } return ""; }; Writer.prototype._inverted = function (name, context, callback) { var value = context.lookup(name); // Use JavaScript's definition of falsy. Include empty arrays. // See https://github.com/janl/mustache.js/issues/186 if (!value || (isArray(value) && value.length === 0)) { return callback(this, context); } return ""; }; Writer.prototype._partial = function (name, context) { if (!(name in this._partialCache) && this._loadPartial) { this.compilePartial(name, this._loadPartial(name)); } var fn = this._partialCache[name]; return fn ? fn(context) : ""; }; Writer.prototype._name = function (name, context) { var value = context.lookup(name); if (typeof value === "function") { value = value.call(context.view); } return (value == null) ? "" : String(value); }; Writer.prototype._escaped = function (name, context) { return exports.escape(this._name(name, context)); }; /** * Calculates the bounds of the section represented by the given `token` in * the original template by drilling down into nested sections to find the * last token that is part of that section. Returns an array of [start, end]. */ function sectionBounds(token) { var start = token[3]; var end = start; var tokens; while ((tokens = token[4]) && tokens.length) { token = tokens[tokens.length - 1]; end = token[3]; } return [start, end]; } /** * Low-level function that compiles the given `tokens` into a function * that accepts two arguments: a Context and a Writer. */ function compileTokens(tokens) { var subRenders = {}; function subRender(i, tokens, template) { if (!subRenders[i]) { var fn = compileTokens(tokens); subRenders[i] = function (writer, context) { return fn(writer, context, template); }; } return subRenders[i]; } function renderFunction(writer, context, template) { var buffer = ""; var token, sectionText; for (var i = 0, len = tokens.length; i < len; ++i) { token = tokens[i]; switch (token[0]) { case "#": sectionText = template.slice.apply(template, sectionBounds(token)); buffer += writer._section(token[1], context, sectionText, subRender(i, token[4], template)); break; case "^": buffer += writer._inverted(token[1], context, subRender(i, token[4], template)); break; case ">": buffer += writer._partial(token[1], context); break; case "&": buffer += writer._name(token[1], context); break; case "name": buffer += writer._escaped(token[1], context); break; case "text": buffer += token[1]; break; } } return buffer; } return renderFunction; } /** * Forms the given array of `tokens` into a nested tree structure where * tokens that represent a section have a fifth item: an array that contains * all tokens in that section. */ function nestTokens(tokens) { var tree = []; var collector = tree; var sections = []; var token, section; for (var i = 0; i < tokens.length; ++i) { token = tokens[i]; switch (token[0]) { case "#": case "^": token[4] = []; sections.push(token); collector.push(token); collector = token[4]; break; case "/": if (sections.length === 0) { throw new Error("Unopened section: " + token[1]); } section = sections.pop(); if (section[1] !== token[1]) { throw new Error("Unclosed section: " + section[1]); } if (sections.length > 0) { collector = sections[sections.length - 1][4]; } else { collector = tree; } break; default: collector.push(token); } } // Make sure there were no open sections when we're done. section = sections.pop(); if (section) { throw new Error("Unclosed section: " + section[1]); } return tree; } /** * Combines the values of consecutive text tokens in the given `tokens` array * to a single token. */ function squashTokens(tokens) { var token, lastToken; for (var i = 0; i < tokens.length; ++i) { token = tokens[i]; if (lastToken && lastToken[0] === "text" && token[0] === "text") { lastToken[1] += token[1]; lastToken[3] = token[3]; tokens.splice(i--, 1); // Remove this token from the array. } else { lastToken = token; } } } function escapeTags(tags) { if (tags.length !== 2) { throw new Error("Invalid tags: " + tags.join(" ")); } return [ new RegExp(escapeRe(tags[0]) + "\\s*"), new RegExp("\\s*" + escapeRe(tags[1])) ]; } /** * Breaks up the given `template` string into a tree of token objects. If * `tags` is given here it must be an array with two string values: the * opening and closing tags used in the template (e.g. ["<%", "%>"]). Of * course, the default is to use mustaches (i.e. Mustache.tags). */ exports.parse = function (template, tags) { tags = tags || exports.tags; var tagRes = escapeTags(tags); var scanner = new Scanner(template); var tokens = [], // Buffer to hold the tokens spaces = [], // Indices of whitespace tokens on the current line hasTag = false, // Is there a {{tag}} on the current line? nonSpace = false; // Is there a non-space char on the current line? // Strips all whitespace tokens array for the current line // if there was a {{#tag}} on it and otherwise only space. function stripSpace() { if (hasTag && !nonSpace) { while (spaces.length) { tokens.splice(spaces.pop(), 1); } } else { spaces = []; } hasTag = false; nonSpace = false; } var start, type, value, chr; while (!scanner.eos()) { start = scanner.pos; value = scanner.scanUntil(tagRes[0]); if (value) { for (var i = 0, len = value.length; i < len; ++i) { chr = value.charAt(i); if (isWhitespace(chr)) { spaces.push(tokens.length); } else { nonSpace = true; } tokens.push(["text", chr, start, start + 1]); start += 1; if (chr === "\n") { stripSpace(); // Check for whitespace on the current line. } } } start = scanner.pos; // Match the opening tag. if (!scanner.scan(tagRes[0])) { break; } hasTag = true; type = scanner.scan(tagRe) || "name"; // Skip any whitespace between tag and value. scanner.scan(whiteRe); // Extract the tag value. if (type === "=") { value = scanner.scanUntil(eqRe); scanner.scan(eqRe); scanner.scanUntil(tagRes[1]); } else if (type === "{") { var closeRe = new RegExp("\\s*" + escapeRe("}" + tags[1])); value = scanner.scanUntil(closeRe); scanner.scan(curlyRe); scanner.scanUntil(tagRes[1]); type = "&"; } else { value = scanner.scanUntil(tagRes[1]); } // Match the closing tag. if (!scanner.scan(tagRes[1])) { throw new Error("Unclosed tag at " + scanner.pos); } tokens.push([type, value, start, scanner.pos]); if (type === "name" || type === "{" || type === "&") { nonSpace = true; } // Set the tags for the next time around. if (type === "=") { tags = value.split(spaceRe); tagRes = escapeTags(tags); } } squashTokens(tokens); return nestTokens(tokens); }; // The high-level clearCache, compile, compilePartial, and render functions // use this default writer. var _writer = new Writer(); /** * Clears all cached templates and partials in the default writer. */ exports.clearCache = function () { return _writer.clearCache(); }; /** * Compiles the given `template` to a reusable function using the default * writer. */ exports.compile = function (template, tags) { return _writer.compile(template, tags); }; /** * Compiles the partial with the given `name` and `template` to a reusable * function using the default writer. */ exports.compilePartial = function (name, template, tags) { return _writer.compilePartial(name, template, tags); }; /** * Renders the `template` with the given `view` and `partials` using the * default writer. */ exports.render = function (template, view, partials) { return _writer.render(template, view, partials); }; // This is here for backwards compatibility with 0.4.x. exports.to_html = function (template, view, partials, send) { var result = exports.render(template, view, partials); if (typeof send === "function") { send(result); } else { return result; } }; return exports; }())));
15,264
Python
.tac
494
24.665992
102
0.581764
devsnd/cherrymusic
1,032
187
111
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,405
item.py
jjjake_internetarchive/internetarchive/item.py
# # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2021 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ internetarchive.item ~~~~~~~~~~~~~~~~~~~~ :copyright: (C) 2012-2021 by Internet Archive. :license: AGPL 3, see LICENSE for more details. """ from __future__ import annotations import io import math import os import sys from copy import deepcopy from fnmatch import fnmatch from functools import total_ordering from logging import getLogger from time import sleep from typing import Mapping, MutableMapping from urllib.parse import quote from xml.parsers.expat import ExpatError from requests import Request, Response from requests.exceptions import HTTPError from tqdm import tqdm from internetarchive import catalog from internetarchive.auth import S3Auth from internetarchive.files import File from internetarchive.iarequest import MetadataRequest, S3Request from internetarchive.utils import ( IdentifierListAsItems, IterableToFileAdapter, chunk_generator, get_file_size, get_md5, get_s3_xml_text, is_dir, iter_directory, json, norm_filepath, recursive_file_count_and_size, validate_s3_identifier, ) log = getLogger(__name__) @total_ordering class BaseItem: EXCLUDED_ITEM_METADATA_KEYS = ('workable_servers', 'server') def __init__( self, identifier: str | None = None, item_metadata: Mapping | None = None, ): # Default attributes. self.identifier = identifier self.item_metadata = item_metadata or {} self.exists = False # Archive.org metadata attributes. self.metadata: dict = {} self.files: list[dict] = [] self.created = None self.d1 = None self.d2 = None self.dir = None self.files_count = None self.item_size = None self.reviews: list = [] self.server = None self.uniq = None self.updated = None self.tasks = None self.is_dark = None # Load item. self.load() def __repr__(self) -> str: notloaded = ', item_metadata={}' if not self.exists else '' return f'{self.__class__.__name__}(identifier={self.identifier!r}{notloaded})' def load(self, item_metadata: Mapping | None = None) -> None: if item_metadata: self.item_metadata = item_metadata self.exists = bool(self.item_metadata) for key in self.item_metadata: setattr(self, key, self.item_metadata[key]) if not self.identifier: self.identifier = self.metadata.get('identifier') mc = self.metadata.get('collection', []) # TODO: The `type: ignore` on the following line should be removed. See #518 self.collection = IdentifierListAsItems(mc, self.session) # type: ignore def __eq__(self, other) -> bool: return (self.item_metadata == other.item_metadata or (self.item_metadata.keys() == other.item_metadata.keys() and all(self.item_metadata[x] == other.item_metadata[x] for x in self.item_metadata if x not in self.EXCLUDED_ITEM_METADATA_KEYS))) def __le__(self, other) -> bool: return self.identifier <= other.identifier def __hash__(self) -> int: without_excluded_keys = { k: v for k, v in self.item_metadata.items() if k not in self.EXCLUDED_ITEM_METADATA_KEYS} return hash(json.dumps(without_excluded_keys, sort_keys=True, check_circular=False)) # type: ignore class Item(BaseItem): """This class represents an archive.org item. Generally this class should not be used directly, but rather via the ``internetarchive.get_item()`` function:: >>> from internetarchive import get_item >>> item = get_item('stairs') >>> print(item.metadata) Or to modify the metadata for an item:: >>> metadata = {'title': 'The Stairs'} >>> item.modify_metadata(metadata) >>> print(item.metadata['title']) 'The Stairs' This class also uses IA's S3-like interface to upload files to an item. You need to supply your IAS3 credentials in environment variables in order to upload:: >>> item.upload('myfile.tar', access_key='Y6oUrAcCEs4sK8ey', ... secret_key='youRSECRETKEYzZzZ') True You can retrieve S3 keys here: `https://archive.org/account/s3.php <https://archive.org/account/s3.php>`__ """ def __init__( self, archive_session, identifier: str, item_metadata: Mapping | None = None, ): """ :param archive_session: :class:`ArchiveSession <ArchiveSession>` :param identifier: The globally unique Archive.org identifier for this item. An identifier is composed of any unique combination of alphanumeric characters, underscore ( _ ) and dash ( - ). While there are no official limits it is strongly suggested that they be between 5 and 80 characters in length. Identifiers must be unique across the entirety of Internet Archive, not simply unique within a single collection. Once defined an identifier can not be changed. It will travel with the item or object and is involved in every manner of accessing or referring to the item. :param item_metadata: The Archive.org item metadata used to initialize this item. If no item metadata is provided, it will be retrieved from Archive.org using the provided identifier. """ self.session = archive_session super().__init__(identifier, item_metadata) self.urls = Item.URLs(self) if self.metadata.get('title'): # A copyable link to the item, in MediaWiki format details = self.urls.details # type: ignore self.wikilink = f'* [{details} {self.identifier}] -- {self.metadata["title"]}' class URLs: def __init__(self, itm_obj): self._itm_obj = itm_obj self._paths = [] self._make_URL('details') self._make_URL('metadata') self._make_URL('download') self._make_URL('history') self._make_URL('edit') self._make_URL('editxml') self._make_URL('manage') if self._itm_obj.metadata.get('mediatype') == 'collection': self._make_tab_URL('about') self._make_tab_URL('collection') def _make_tab_URL(self, tab: str) -> None: """Make URLs for the separate tabs of Collections details page.""" self._make_URL(tab, self.details + f'&tab={tab}') # type: ignore DEFAULT_URL_FORMAT = ('{0.session.protocol}//{0.session.host}' '/{path}/{0.identifier}') def _make_URL(self, path: str, url_format: str = DEFAULT_URL_FORMAT) -> None: setattr(self, path, url_format.format(self._itm_obj, path=path)) self._paths.append(path) def __str__(self) -> str: return f'URLs ({", ".join(self._paths)}) for {self._itm_obj.identifier}' def refresh(self, item_metadata: Mapping | None = None, **kwargs) -> None: if not item_metadata: item_metadata = self.session.get_metadata(self.identifier, **kwargs) self.load(item_metadata) def identifier_available(self) -> bool: """Check if the item identifier is available for creating a new item. :return: `True` if identifier is available, or `False` if it is not available. """ url = f'{self.session.protocol}//{self.session.host}/services/check_identifier.php' params = {'output': 'json', 'identifier': self.identifier} response = self.session.get(url, params=params) availability = response.json()['code'] return availability == 'available' def get_task_summary( self, params: Mapping | None = None, request_kwargs: Mapping | None = None, ) -> dict: """Get a summary of the item's pending tasks. :param params: Params to send with your request. :returns: A summary of the item's pending tasks. """ return self.session.get_tasks_summary(self.identifier, params, request_kwargs) def no_tasks_pending( self, params: Mapping | None = None, request_kwargs: Mapping | None = None, ) -> bool: """Check if there is any pending task for the item. :param params: Params to send with your request. :returns: `True` if no tasks are pending, otherwise `False`. """ return all(x == 0 for x in self.get_task_summary(params, request_kwargs).values()) def get_all_item_tasks( self, params: dict | None = None, request_kwargs: Mapping | None = None, ) -> list[catalog.CatalogTask]: """Get a list of all tasks for the item, pending and complete. :param params: Query parameters, refer to `Tasks API <https://archive.org/services/docs/api/tasks.html>`_ for available parameters. :param request_kwargs: Keyword arguments that :py:func:`requests.get` takes. :returns: A list of all tasks for the item, pending and complete. """ params = params or {} params.update({'catalog': 1, 'history': 1}) return self.session.get_tasks(self.identifier, params, request_kwargs) def get_history( self, params: Mapping | None = None, request_kwargs: Mapping | None = None, ) -> list[catalog.CatalogTask]: """Get a list of completed catalog tasks for the item. :param params: Params to send with your request. :returns: A list of completed catalog tasks for the item. """ return list(self.session.iter_history(self.identifier, params, request_kwargs)) def get_catalog( self, params: Mapping | None = None, request_kwargs: Mapping | None = None, ) -> list[catalog.CatalogTask]: """Get a list of pending catalog tasks for the item. :param params: Params to send with your request. :returns: A list of pending catalog tasks for the item. """ return list(self.session.iter_catalog(self.identifier, params, request_kwargs)) def derive(self, priority: int = 0, remove_derived: str | None = None, reduced_priority: bool = False, data: MutableMapping | None = None, headers: Mapping | None = None, request_kwargs: Mapping | None = None) -> Response: """Derive an item. :param priority: Task priority from 10 to -10 [default: 0] :param remove_derived: You can use wildcards ("globs") to only remove *some* prior derivatives. For example, "*" (typed without the quotation marks) specifies that all derivatives (in the item's top directory) are to be rebuilt. "*.mp4" specifies that all "*.mp4" deriviatives are to be rebuilt. "{*.gif,*thumbs/*.jpg}" specifies that all GIF and thumbs are to be rebuilt. :param reduced_priority: Submit your derive at a lower priority. This option is helpful to get around rate-limiting. Your task will more likely be accepted, but it might not run for a long time. Note that you still may be subject to rate-limiting. :returns: :class:`requests.Response` """ data = data or {} if remove_derived is not None: if not data.get('args'): data['args'] = {'remove_derived': remove_derived} else: data['args'].update({'remove_derived': remove_derived}) r = self.session.submit_task(self.identifier, 'derive.php', priority=priority, data=data, headers=headers, reduced_priority=reduced_priority, request_kwargs=request_kwargs) r.raise_for_status() return r def fixer(self, ops: list | str | None = None, priority: int | str | None = None, reduced_priority: bool = False, data: MutableMapping | None = None, headers: Mapping | None = None, request_kwargs: Mapping | None = None) -> Response: """Submit a fixer task on an item. :param ops: The fixer operation(s) to run on the item [default: noop]. :param priority: The task priority. :param reduced_priority: Submit your derive at a lower priority. This option is helpful to get around rate-limiting. Your task will more likely be accepted, but it might not run for a long time. Note that you still may be subject to rate-limiting. This is different than ``priority`` in that it will allow you to possibly avoid rate-limiting. :param data: Additional parameters to submit with the task. :returns: :class:`requests.Response` """ data = data or {} ops = ops or ['noop'] if not isinstance(ops, (list, tuple, set)): ops = [ops] data['args'] = data.get('args') or {} for op in ops: data['args'][op] = '1' r = self.session.submit_task(self.identifier, 'fixer.php', priority=priority, data=data, headers=headers, reduced_priority=reduced_priority, request_kwargs=request_kwargs) r.raise_for_status() return r def undark(self, comment: str, priority: int | str | None = None, reduced_priority: bool = False, data: Mapping | None = None, request_kwargs: Mapping | None = None) -> Response: """Undark the item. :param comment: The curation comment explaining reason for undarking item :param priority: The task priority. :param reduced_priority: Submit your derive at a lower priority. This option is helpful to get around rate-limiting. Your task will more likely be accepted, but it might not run for a long time. Note that you still may be subject to rate-limiting. This is different than ``priority`` in that it will allow you to possibly avoid rate-limiting. :param data: Additional parameters to submit with the task. :returns: :class:`requests.Response` """ r = self.session.submit_task(self.identifier, 'make_undark.php', comment=comment, priority=priority, data=data, reduced_priority=reduced_priority, request_kwargs=request_kwargs) r.raise_for_status() return r # TODO: dark and undark have different order for data and reduced_pripoity def dark(self, comment: str, priority: int | str | None = None, data: Mapping | None = None, reduced_priority: bool = False, request_kwargs: Mapping | None = None) -> Response: """Dark the item. :param comment: The curation comment explaining reason for darking item :param priority: The task priority. :param reduced_priority: Submit your derive at a lower priority. This option is helpful to get around rate-limiting. Your task will more likely be accepted, but it might not run for a long time. Note that you still may be subject to rate-limiting. This is different than ``priority`` in that it will allow you to possibly avoid rate-limiting. :param data: Additional parameters to submit with the task. :returns: :class:`requests.Response` """ r = self.session.submit_task(self.identifier, 'make_dark.php', comment=comment, priority=priority, data=data, reduced_priority=reduced_priority, request_kwargs=request_kwargs) r.raise_for_status() return r def get_review(self) -> Response: u = f'{self.session.protocol}//{self.session.host}/services/reviews.php' p = {'identifier': self.identifier} a = S3Auth(self.session.access_key, self.session.secret_key) r = self.session.get(u, params=p, auth=a) r.raise_for_status() return r def delete_review(self, username=None, screenname=None, itemname=None) -> Response: u = f'{self.session.protocol}//{self.session.host}/services/reviews.php' p = {'identifier': self.identifier} d = None if username: d = {'username': username} elif screenname: d = {'screenname': screenname} elif itemname: d = {'itemname': itemname} a = S3Auth(self.session.access_key, self.session.secret_key) r = self.session.delete(u, params=p, data=d, auth=a) r.raise_for_status() return r def review(self, title, body, stars=None) -> Response: u = f'{self.session.protocol}//{self.session.host}/services/reviews.php' p = {'identifier': self.identifier} d = {'title': title, 'body': body} if stars: d['stars'] = stars a = S3Auth(self.session.access_key, self.session.secret_key) r = self.session.post(u, params=p, data=json.dumps(d), auth=a) r.raise_for_status() return r def get_file(self, file_name: str, file_metadata: Mapping | None = None) -> File: """Get a :class:`File <File>` object for the named file. :param file_metadata: a dict of metadata for the given file. :returns: An :class:`internetarchive.File <File>` object. """ return File(self, file_name, file_metadata) def get_files(self, files: File | list[File] | None = None, formats: str | list[str] | None = None, glob_pattern: str | None = None, exclude_pattern: str | None = None, on_the_fly: bool = False): files = files or [] formats = formats or [] exclude_pattern = exclude_pattern or '' on_the_fly = bool(on_the_fly) if not isinstance(files, (list, tuple, set)): files = [files] if not isinstance(formats, (list, tuple, set)): formats = [formats] item_files = deepcopy(self.files) # Add support for on-the-fly files (e.g. EPUB). if on_the_fly: otf_files = [ ('EPUB', f'{self.identifier}.epub'), ('MOBI', f'{self.identifier}.mobi'), ('DAISY', f'{self.identifier}_daisy.zip'), ('MARCXML', f'{self.identifier}_archive_marc.xml'), ] for format, file_name in otf_files: item_files.append({'name': file_name, 'format': format, 'otf': True}) if not any(k for k in [files, formats, glob_pattern]): for f in item_files: yield self.get_file(str(f.get('name')), file_metadata=f) for f in item_files: if f.get('name') in files: yield self.get_file(str(f.get('name'))) elif f.get('format') in formats: yield self.get_file(str(f.get('name'))) elif glob_pattern: if not isinstance(glob_pattern, list): patterns = glob_pattern.split('|') else: patterns = glob_pattern if not isinstance(exclude_pattern, list): exclude_patterns = exclude_pattern.split('|') else: exclude_patterns = exclude_pattern for p in patterns: if fnmatch(f.get('name', ''), p): if not any(fnmatch(f.get('name', ''), e) for e in exclude_patterns): yield self.get_file(str(f.get('name'))) def download(self, files: File | list[File] | None = None, formats: str | list[str] | None = None, glob_pattern: str | None = None, exclude_pattern: str | None = None, dry_run: bool = False, verbose: bool = False, ignore_existing: bool = False, checksum: bool = False, checksum_archive: bool = False, destdir: str | None = None, no_directory: bool = False, retries: int | None = None, item_index: int | None = None, ignore_errors: bool = False, on_the_fly: bool = False, return_responses: bool = False, no_change_timestamp: bool = False, ignore_history_dir: bool = False, source: str | list[str] | None = None, exclude_source: str | list[str] | None = None, stdout: bool = False, params: Mapping | None = None, timeout: int | float | tuple[int, float] | None = None ) -> list[Request | Response]: """Download files from an item. :param files: Only download files matching given file names. :param formats: Only download files matching the given Formats. :param glob_pattern: Only download files matching the given glob pattern. :param exclude_pattern: Exclude files whose filename matches the given glob pattern. :param dry_run: Output download URLs to stdout, don't download anything. :param verbose: Turn on verbose output. :param ignore_existing: Skip files that already exist locally. :param checksum: Skip downloading file based on checksum. :param checksum_archive: Skip downloading file based on checksum, and skip checksum validation if it already succeeded (will create and use _checksum_archive.txt). :param destdir: The directory to download files to. :param no_directory: Download files to current working directory rather than creating an item directory. :param retries: The number of times to retry on failed requests. :param item_index: The index of the item for displaying progress in bulk downloads. :param ignore_errors: Don't fail if a single file fails to download, continue to download other files. :param on_the_fly: Download on-the-fly files (i.e. derivative EPUB, MOBI, DAISY files). :param return_responses: Rather than downloading files to disk, return a list of response objects. :param no_change_timestamp: If True, leave the time stamp as the current time instead of changing it to that given in the original archive. :param source: Filter files based on their source value in files.xml (i.e. `original`, `derivative`, `metadata`). :param exclude_source: Filter files based on their source value in files.xml (i.e. `original`, `derivative`, `metadata`). :param params: URL parameters to send with download request (e.g. `cnt=0`). :param ignore_history_dir: Do not download any files from the history dir. This param defaults to ``False``. :returns: True if if all files have been downloaded successfully. """ dry_run = bool(dry_run) verbose = bool(verbose) ignore_existing = bool(ignore_existing) ignore_errors = bool(ignore_errors) checksum = bool(checksum) checksum_archive = bool(checksum_archive) no_directory = bool(no_directory) return_responses = bool(return_responses) no_change_timestamp = bool(no_change_timestamp) ignore_history_dir = bool(ignore_history_dir) params = params or None if source: if not isinstance(source, list): source = [source] if exclude_source: if not isinstance(exclude_source, list): exclude_source = [exclude_source] if stdout: fileobj = os.fdopen(sys.stdout.fileno(), "wb", closefd=False) verbose = False else: fileobj = None if not dry_run: if item_index and verbose: print(f'{self.identifier} ({item_index}):', file=sys.stderr) elif item_index is None and verbose: print(f'{self.identifier}:', file=sys.stderr) if self.is_dark: msg = f'skipping {self.identifier}, item is dark' log.warning(msg) if verbose: print(f' {msg}', file=sys.stderr) return [] elif self.metadata == {}: msg = f'skipping {self.identifier}, item does not exist.' log.warning(msg) if verbose: print(f' {msg}', file=sys.stderr) return [] if files: files = self.get_files(files, on_the_fly=on_the_fly) else: files = self.get_files(on_the_fly=on_the_fly) if formats: files = self.get_files(formats=formats, on_the_fly=on_the_fly) if glob_pattern: files = self.get_files( glob_pattern=glob_pattern, exclude_pattern=exclude_pattern, on_the_fly=on_the_fly ) if stdout: files = list(files) # type: ignore errors = [] downloaded = 0 responses = [] file_count = 0 for f in files: # type: ignore if ignore_history_dir is True: if f.name.startswith('history/'): continue if source and not any(f.source == x for x in source): continue if exclude_source and any(f.source == x for x in exclude_source): continue file_count += 1 if no_directory: path = f.name else: path = os.path.join(str(self.identifier), f.name) if dry_run: print(f.url) continue if stdout and file_count < len(files): # type: ignore ors = True else: ors = False r = f.download(path, verbose, ignore_existing, checksum, checksum_archive, destdir, retries, ignore_errors, fileobj, return_responses, no_change_timestamp, params, None, stdout, ors, timeout) if return_responses: responses.append(r) if r is False: errors.append(f.name) else: downloaded += 1 if file_count == 0: msg = f'skipping {self.identifier}, no matching files found.' log.info(msg) if verbose: print(f' {msg}', file=sys.stderr) return [] return responses if return_responses else errors def modify_metadata(self, metadata: Mapping, target: str | None = None, append: bool = False, expect: Mapping | None = None, append_list: bool = False, insert: bool = False, priority: int = 0, access_key: str | None = None, secret_key: str | None = None, debug: bool = False, headers: Mapping | None = None, request_kwargs: Mapping | None = None, timeout: int | float | None = None, refresh: bool = True) -> Request | Response: """Modify the metadata of an existing item on Archive.org. Note: The Metadata Write API does not yet comply with the latest Json-Patch standard. It currently complies with `version 02 <https://tools.ietf.org/html/draft-ietf-appsawg-json-patch-02>`__. :param metadata: Metadata used to update the item. :param target: Set the metadata target to update. :param priority: Set task priority. :param append: Append value to an existing multi-value metadata field. :param expect: Provide a dict of expectations to be tested server-side before applying patch to item metadata. :param append_list: Append values to an existing multi-value metadata field. No duplicate values will be added. :param refresh: Refresh the item metadata after the request. :returns: A Request if debug else a Response. Usage:: >>> import internetarchive >>> item = internetarchive.Item('mapi_test_item1') >>> md = {'new_key': 'new_value', 'foo': ['bar', 'bar2']} >>> item.modify_metadata(md) """ append = bool(append) access_key = access_key or self.session.access_key secret_key = secret_key or self.session.secret_key debug = bool(debug) headers = headers or {} expect = expect or {} request_kwargs = request_kwargs or {} if timeout: request_kwargs["timeout"] = float(timeout) # type: ignore else: request_kwargs["timeout"] = 60 # type: ignore _headers = self.session.headers.copy() _headers.update(headers) url = f'{self.session.protocol}//{self.session.host}/metadata/{self.identifier}' # TODO: currently files and metadata targets do not support dict's, # but they might someday?? refactor this check. source_metadata = self.item_metadata request = MetadataRequest( method='POST', url=url, metadata=metadata, headers=_headers, source_metadata=source_metadata, target=target, priority=priority, access_key=access_key, secret_key=secret_key, append=append, expect=expect, append_list=append_list, insert=insert) # Must use Session.prepare_request to make sure session settings # are used on request! prepared_request = request.prepare() if debug: return prepared_request resp = self.session.send(prepared_request, **request_kwargs) # Re-initialize the Item object with the updated metadata. if refresh: self.refresh() return resp # TODO: `list` parameter name shadows the Python builtin def remove_from_simplelist(self, parent, list) -> Response: """Remove item from a simplelist. :returns: :class:`requests.Response` """ patch = { 'op': 'delete', 'parent': parent, 'list': list, } data = { '-patch': json.dumps(patch), '-target': 'simplelists', } r = self.session.post(self.urls.metadata, data=data) # type: ignore return r def upload_file(self, body, key: str | None = None, metadata: Mapping | None = None, file_metadata: Mapping | None = None, headers: dict | None = None, access_key: str | None = None, secret_key: str | None = None, queue_derive: bool = False, verbose: bool = False, verify: bool = False, checksum: bool = False, delete: bool = False, retries: int | None = None, retries_sleep: int | None = None, debug: bool = False, validate_identifier: bool = False, request_kwargs: MutableMapping | None = None, set_scanner: bool = True) -> Request | Response: """Upload a single file to an item. The item will be created if it does not exist. :type body: Filepath or file-like object. :param body: File or data to be uploaded. :param key: Remote filename. :param metadata: Metadata used to create a new item. :param file_metadata: File-level metadata to add to the files.xml entry for the file being uploaded. :param headers: Add additional IA-S3 headers to request. :param queue_derive: Set to False to prevent an item from being derived after upload. :param verify: Verify local MD5 checksum matches the MD5 checksum of the file received by IAS3. :param checksum: Skip based on checksum. :param delete: Delete local file after the upload has been successfully verified. :param retries: Number of times to retry the given request if S3 returns a 503 SlowDown error. :param retries_sleep: Amount of time to sleep between ``retries``. :param verbose: Print progress to stdout. :param debug: Set to True to print headers to stdout, and exit without sending the upload request. :param validate_identifier: Set to True to validate the identifier before uploading the file. Usage:: >>> import internetarchive >>> item = internetarchive.Item('identifier') >>> item.upload_file('/path/to/image.jpg', ... key='photos/image1.jpg') True """ # Set defaults. headers = headers or {} metadata = metadata or {} file_metadata = file_metadata or {} access_key = access_key or self.session.access_key secret_key = secret_key or self.session.secret_key queue_derive = bool(queue_derive) verbose = bool(verbose) verify = bool(verify) delete = bool(delete) # Set checksum after delete. checksum = delete or checksum retries = retries or 0 retries_sleep = retries_sleep or 30 debug = bool(debug) validate_identifier = bool(validate_identifier) request_kwargs = request_kwargs or {} if 'timeout' not in request_kwargs: request_kwargs['timeout'] = 120 md5_sum = None _headers = headers.copy() if not hasattr(body, 'read'): filename = body body = open(body, 'rb') else: filename = key or body.name size = get_file_size(body) # Support for uploading empty files. if size == 0: _headers['Content-Length'] = '0' if not _headers.get('x-archive-size-hint'): _headers['x-archive-size-hint'] = str(size) # Build IA-S3 URL. if validate_identifier: validate_s3_identifier(self.identifier or "") key = norm_filepath(filename).split('/')[-1] if key is None else key base_url = f'{self.session.protocol}//s3.us.archive.org/{self.identifier}' url = f'{base_url}/{quote(norm_filepath(key).lstrip("/").encode("utf-8"))}' # Skip based on checksum. if checksum: md5_sum = get_md5(body) ia_file = self.get_file(key) if (not self.tasks) and (ia_file) and (ia_file.md5 == md5_sum): log.info(f'{key} already exists: {url}') if verbose: print(f' {key} already exists, skipping.', file=sys.stderr) if delete: log.info( f'{key} successfully uploaded to ' f'https://archive.org/download/{self.identifier}/{key} ' 'and verified, deleting local copy') body.close() os.remove(filename) # Return an empty response object if checksums match. # TODO: Is there a better way to handle this? body.close() return Response() # require the Content-MD5 header when delete is True. if verify or delete: if not md5_sum: md5_sum = get_md5(body) _headers['Content-MD5'] = md5_sum def _build_request(): body.seek(0, os.SEEK_SET) if verbose: try: # hack to raise exception so we get some output for # empty files. if size == 0: raise Exception chunk_size = 1048576 expected_size = math.ceil(size / chunk_size) chunks = chunk_generator(body, chunk_size) progress_generator = tqdm(chunks, desc=f' uploading {key}', dynamic_ncols=True, total=expected_size, unit='MiB') data = None # pre_encode is needed because http doesn't know that it # needs to encode a TextIO object when it's wrapped # in the Iterator from tqdm. # So, this FileAdapter provides pre-encoded output data = IterableToFileAdapter( progress_generator, size, pre_encode=isinstance(body, io.TextIOBase) ) except Exception: print(f' uploading {key}', file=sys.stderr) data = body else: data = body _headers.update(self.session.headers) request = S3Request(method='PUT', url=url, headers=_headers, data=data, metadata=metadata, file_metadata=file_metadata, access_key=access_key, secret_key=secret_key, queue_derive=queue_derive, set_scanner=set_scanner) return request if debug: prepared_request = self.session.prepare_request(_build_request()) body.close() return prepared_request else: try: while True: error_msg = ('s3 is overloaded, sleeping for ' f'{retries_sleep} seconds and retrying. ' f'{retries} retries left.') if retries > 0: if self.session.s3_is_overloaded(access_key=access_key): sleep(retries_sleep) log.info(error_msg) if verbose: print(f' warning: {error_msg}', file=sys.stderr) retries -= 1 continue request = _build_request() prepared_request = request.prepare() # chunked transfer-encoding is NOT supported by IA-S3. # It should NEVER be set. Requests adds it in certain # scenarios (e.g. if content-length is 0). Stop it. if prepared_request.headers.get('transfer-encoding') == 'chunked': del prepared_request.headers['transfer-encoding'] response = self.session.send(prepared_request, stream=True, **request_kwargs) if (response.status_code == 503) and (retries > 0): if b'appears to be spam' in response.content: log.info('detected as spam, upload failed') break log.info(error_msg) if verbose: print(f' warning: {error_msg}', file=sys.stderr) sleep(retries_sleep) retries -= 1 continue else: if response.status_code == 503: log.info('maximum retries exceeded, upload failed.') break response.raise_for_status() log.info(f'uploaded {key} to {url}') if delete and response.status_code == 200: log.info( f'{key} successfully uploaded to ' f'https://archive.org/download/{self.identifier}/{key} and verified, ' 'deleting local copy') body.close() os.remove(filename) response.close() return response except HTTPError as exc: try: msg = get_s3_xml_text(exc.response.content) # type: ignore except ExpatError: # probably HTTP 500 error and response is invalid XML msg = ('IA S3 returned invalid XML ' # type: ignore f'(HTTP status code {exc.response.status_code}). ' 'This is a server side error which is either temporary, ' 'or requires the intervention of IA admins.') error_msg = f' error uploading {key} to {self.identifier}, {msg}' log.error(error_msg) if verbose: print(f' error uploading {key}: {msg}', file=sys.stderr) # Raise HTTPError with error message. raise type(exc)(error_msg, response=exc.response, request=exc.request) finally: body.close() def upload(self, files, metadata: Mapping | None = None, headers: dict | None = None, access_key: str | None = None, secret_key: str | None = None, queue_derive=None, # TODO: True if None?? verbose: bool = False, verify: bool = False, checksum: bool = False, delete: bool = False, retries: int | None = None, retries_sleep: int | None = None, debug: bool = False, validate_identifier: bool = False, request_kwargs: dict | None = None, set_scanner: bool = True) -> list[Request | Response]: r"""Upload files to an item. The item will be created if it does not exist. :type files: str, file, list, tuple, dict :param files: The filepaths or file-like objects to upload. :param \*\*kwargs: Optional arguments that :func:`Item.upload_file()` takes. :returns: A list of :class:`requests.Response` objects. Usage:: >>> import internetarchive >>> item = internetarchive.Item('identifier') >>> md = {'mediatype': 'image', 'creator': 'Jake Johnson'} >>> item.upload('/path/to/image.jpg', metadata=md, queue_derive=False) [<Response [200]>] Uploading multiple files:: >>> r = item.upload(['file1.txt', 'file2.txt']) >>> r = item.upload([fileobj, fileobj2]) >>> r = item.upload(('file1.txt', 'file2.txt')) Uploading file objects: >>> import io >>> f = io.BytesIO(b'some initial binary data: \x00\x01') >>> r = item.upload({'remote-name.txt': f}) >>> f = io.BytesIO(b'some more binary data: \x00\x01') >>> f.name = 'remote-name.txt' >>> r = item.upload(f) *Note: file objects must either have a name attribute, or be uploaded in a dict where the key is the remote-name* Setting the remote filename with a dict:: >>> r = item.upload({'remote-name.txt': '/path/to/local/file.txt'}) """ queue_derive = True if queue_derive is None else queue_derive remote_dir_name = None total_files = 0 if isinstance(files, dict): if files.get('name'): files = [files] total_files = 1 else: files = list(files.items()) if not isinstance(files, (list, tuple)): files = [files] if all(isinstance(f, dict) and f.get('name') for f in files): total_files = len(files) responses = [] file_index = 0 headers = headers or {} if (queue_derive or not headers.get('x-archive-size-hint')) and total_files == 0: total_files, total_size = recursive_file_count_and_size(files, item=self, checksum=checksum) if not headers.get('x-archive-size-hint'): headers['x-archive-size-hint'] = str(total_size) file_metadata = None for f in files: if isinstance(f, dict): if f.get('name'): file_metadata = f.copy() del file_metadata['name'] f = f['name'] if ((isinstance(f, str) and is_dir(f)) or (isinstance(f, tuple) and is_dir(f[-1]))): if isinstance(f, tuple): remote_dir_name = f[0].strip('/') f = f[-1] for filepath, key in iter_directory(f): file_index += 1 # Set derive header if queue_derive is True, # and this is the last request being made. if queue_derive is True and file_index >= total_files: _queue_derive = True else: _queue_derive = False if not f.endswith('/'): if remote_dir_name: key = f'{remote_dir_name}{f}/{key}' else: key = f'{f}/{key}' elif remote_dir_name: key = f'{remote_dir_name}/{key}' key = norm_filepath(key) resp = self.upload_file(filepath, key=key, metadata=metadata, file_metadata=file_metadata, headers=headers, access_key=access_key, secret_key=secret_key, queue_derive=_queue_derive, verbose=verbose, verify=verify, checksum=checksum, delete=delete, retries=retries, retries_sleep=retries_sleep, debug=debug, validate_identifier=validate_identifier, request_kwargs=request_kwargs, set_scanner=set_scanner) responses.append(resp) else: file_index += 1 # Set derive header if queue_derive is True, # and this is the last request being made. # if queue_derive is True and file_index >= len(files): if queue_derive is True and file_index >= total_files: _queue_derive = True else: _queue_derive = False if not isinstance(f, (list, tuple)): key, body = (None, f) else: key, body = f if key and not isinstance(key, str): key = str(key) resp = self.upload_file(body, key=key, metadata=metadata, file_metadata=file_metadata, headers=headers, access_key=access_key, secret_key=secret_key, queue_derive=_queue_derive, verbose=verbose, verify=verify, checksum=checksum, delete=delete, retries=retries, retries_sleep=retries_sleep, debug=debug, validate_identifier=validate_identifier, request_kwargs=request_kwargs, set_scanner=set_scanner) responses.append(resp) return responses class Collection(Item): """This class represents an archive.org collection.""" def __init__(self, *args, **kwargs): self.searches = {} if isinstance(args[0], Item): orig = args[0] args = (orig.session, orig.identifier, orig.item_metadata) super().__init__(*args, **kwargs) if self.metadata.get('mediatype', 'collection') != 'collection': raise ValueError('mediatype is not "collection"!') deflt_srh = f'collection:{self.identifier}' self._make_search('contents', self.metadata.get('search_collection', deflt_srh)) self._make_search('subcollections', f'{deflt_srh} AND mediatype:collection') def _do_search(self, name: str, query: str): rtn = self.searches.setdefault( name, self.session.search_items(query, fields=['identifier'])) if not hasattr(self, f'{name}_count'): setattr(self, f'{name}_count', self.searches[name].num_found) return rtn.iter_as_items() def _make_search(self, name: str, query: str): setattr(self, name, lambda: self._do_search(name, query))
54,346
Python
.py
1,134
32.124339
94
0.52006
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,406
config.py
jjjake_internetarchive/internetarchive/config.py
# # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2019 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ internetarchive.config ~~~~~~~~~~~~~~~~~~~~~~ :copyright: (C) 2012-2019 by Internet Archive. :license: AGPL 3, see LICENSE for more details. """ from __future__ import annotations import os from collections import defaultdict from configparser import RawConfigParser from typing import Mapping import requests from internetarchive import auth from internetarchive.exceptions import AuthenticationError from internetarchive.utils import deep_update def get_auth_config(email: str, password: str, host: str = 'archive.org') -> dict: u = f'https://{host}/services/xauthn/' p = {'op': 'login'} d = {'email': email, 'password': password} r = requests.post(u, params=p, data=d, timeout=10) j = r.json() if not j.get('success'): try: msg = j['values']['reason'] except KeyError: msg = j['error'] if msg == 'account_not_found': msg = 'Account not found, check your email and try again.' elif msg == 'account_bad_password': msg = 'Incorrect password, try again.' else: msg = f'Authentication failed: {msg}' raise AuthenticationError(msg) auth_config = { 's3': { 'access': j['values']['s3']['access'], 'secret': j['values']['s3']['secret'], }, 'cookies': { 'logged-in-user': j['values']['cookies']['logged-in-user'], 'logged-in-sig': j['values']['cookies']['logged-in-sig'], }, 'general': { 'screenname': j['values']['screenname'], } } return auth_config def write_config_file(auth_config: Mapping, config_file=None): config_file, is_xdg, config = parse_config_file(config_file) # S3 Keys. access = auth_config.get('s3', {}).get('access') secret = auth_config.get('s3', {}).get('secret') config.set('s3', 'access', access) config.set('s3', 'secret', secret) # Cookies. cookies = auth_config.get('cookies', {}) config.set('cookies', 'logged-in-user', cookies.get('logged-in-user')) config.set('cookies', 'logged-in-sig', cookies.get('logged-in-sig')) # General. screenname = auth_config.get('general', {}).get('screenname') config.set('general', 'screenname', screenname) # Create directory if needed. config_directory = os.path.dirname(config_file) if is_xdg and not os.path.exists(config_directory): # os.makedirs does not apply the mode for intermediate directories since Python 3.7. # The XDG Base Dir spec requires that the XDG_CONFIG_HOME directory be created with mode 700. # is_xdg will be True iff config_file is ${XDG_CONFIG_HOME}/internetarchive/ia.ini. # So create grandparent first if necessary then parent to ensure both have the right mode. os.makedirs(os.path.dirname(config_directory), mode=0o700, exist_ok=True) os.mkdir(config_directory, 0o700) # Write config file. with open(config_file, 'w') as fh: os.chmod(config_file, 0o600) config.write(fh) return config_file def parse_config_file(config_file=None): config = RawConfigParser() is_xdg = False if not config_file: candidates = [] if os.environ.get('IA_CONFIG_FILE'): candidates.append(os.environ['IA_CONFIG_FILE']) xdg_config_home = os.environ.get('XDG_CONFIG_HOME') if not xdg_config_home or not os.path.isabs(xdg_config_home): # Per the XDG Base Dir specification, this should be $HOME/.config. Unfortunately, $HOME # does not exist on all systems. Therefore, we use ~/.config here. On a POSIX-compliant # system, where $HOME must always be set, the XDG spec will be followed precisely. xdg_config_home = os.path.join(os.path.expanduser('~'), '.config') xdg_config_file = os.path.join(xdg_config_home, 'internetarchive', 'ia.ini') candidates.append(xdg_config_file) candidates.append(os.path.join(os.path.expanduser('~'), '.config', 'ia.ini')) candidates.append(os.path.join(os.path.expanduser('~'), '.ia')) for candidate in candidates: if os.path.isfile(candidate): config_file = candidate break else: # None of the candidates exist, default to IA_CONFIG_FILE if set else XDG config_file = os.environ.get('IA_CONFIG_FILE', xdg_config_file) if config_file == xdg_config_file: is_xdg = True config.read(config_file) if not config.has_section('s3'): config.add_section('s3') config.set('s3', 'access', None) config.set('s3', 'secret', None) if not config.has_section('cookies'): config.add_section('cookies') config.set('cookies', 'logged-in-user', None) config.set('cookies', 'logged-in-sig', None) if config.has_section('general'): for k, _v in config.items('general'): if k in ['secure']: config.set('general', k, config.getboolean('general', k)) if not config.get('general', 'screenname'): config.set('general', 'screenname', None) else: config.add_section('general') config.set('general', 'screenname', None) return (config_file, is_xdg, config) def get_config(config=None, config_file=None) -> dict: _config = config or {} config_file, is_xdg, config = parse_config_file(config_file) if not os.path.isfile(config_file): return _config config_dict: dict = defaultdict(dict) for sec in config.sections(): try: for k, v in config.items(sec): if k is None or v is None: continue config_dict[sec][k] = v except TypeError: pass # Recursive/deep update. deep_update(config_dict, _config) return {k: v for k, v in config_dict.items() if v is not None}
6,727
Python
.py
154
36.61039
101
0.64146
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,407
iarequest.py
jjjake_internetarchive/internetarchive/iarequest.py
# # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2021 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ internetarchive.iarequest ~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (C) 2012-2021 by Internet Archive. :license: AGPL 3, see LICENSE for more details. """ import copy import logging import re from urllib.parse import quote import requests import requests.models from jsonpatch import make_patch from internetarchive import __version__, auth from internetarchive.exceptions import ItemLocateError from internetarchive.utils import delete_items_from_dict, json, needs_quote logger = logging.getLogger(__name__) class S3Request(requests.models.Request): def __init__(self, metadata=None, file_metadata=None, queue_derive=True, access_key=None, secret_key=None, set_scanner=True, **kwargs): super().__init__(**kwargs) if not self.auth: self.auth = auth.S3Auth(access_key, secret_key) # Default empty dicts for dict params. metadata = {} if metadata is None else metadata self.metadata = metadata self.file_metadata = file_metadata self.queue_derive = queue_derive self.set_scanner = set_scanner def prepare(self): p = S3PreparedRequest() p.prepare( method=self.method, url=self.url, headers=self.headers, files=self.files, data=self.data, params=self.params, auth=self.auth, cookies=self.cookies, hooks=self.hooks, # S3Request kwargs. metadata=self.metadata, file_metadata=self.file_metadata, queue_derive=self.queue_derive, set_scanner=self.set_scanner, ) return p class S3PreparedRequest(requests.models.PreparedRequest): def prepare(self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, queue_derive=None, metadata=None, file_metadata=None, set_scanner=None): self.prepare_method(method) self.prepare_url(url, params) self.prepare_headers(headers, metadata, file_metadata=file_metadata, queue_derive=queue_derive, set_scanner=set_scanner) self.prepare_cookies(cookies) self.prepare_body(data, files) self.prepare_auth(auth, url) # Note that prepare_auth must be last to enable authentication schemes # such as OAuth to work on a fully prepared request. # This MUST go after prepare_auth. Authenticators could add a hook self.prepare_hooks(hooks) def prepare_headers(self, headers, metadata, file_metadata=None, queue_derive=True, set_scanner=True): """Convert a dictionary of metadata into S3 compatible HTTP headers, and append headers to ``headers``. :type metadata: dict :param metadata: Metadata to be converted into S3 HTTP Headers and appended to ``headers``. :type headers: dict :param headers: (optional) S3 compatible HTTP headers. """ metadata = {} if metadata is None else metadata file_metadata = {} if file_metadata is None else file_metadata if set_scanner is True: scanner = f'Internet Archive Python library {__version__}' if metadata.get('scanner'): metadata['scanner'] = [metadata['scanner'], scanner] else: metadata['scanner'] = scanner prepared_metadata = prepare_metadata(metadata) prepared_file_metadata = prepare_metadata(file_metadata) headers['x-archive-auto-make-bucket'] = '1' if 'x-archive-queue-derive' not in headers: if queue_derive is False: headers['x-archive-queue-derive'] = '0' else: headers['x-archive-queue-derive'] = '1' def _prepare_metadata_headers(prepared_metadata, meta_type='meta'): for meta_key, meta_value in prepared_metadata.items(): # Encode arrays into JSON strings because Archive.org does not # yet support complex metadata structures in # <identifier>_meta.xml. if isinstance(meta_value, dict): meta_value = json.dumps(meta_value) # Convert the metadata value into a list if it is not already # iterable. if (isinstance(meta_value, str) or not hasattr(meta_value, '__iter__')): meta_value = [meta_value] # Convert metadata items into HTTP headers and add to # ``headers`` dict. for i, value in enumerate(meta_value): if not value: continue header_key = f'x-archive-{meta_type}{i:02d}-{meta_key}' if (isinstance(value, str) and needs_quote(value)): value = f'uri({quote(value)})' # because rfc822 http headers disallow _ in names, IA-S3 will # translate two hyphens in a row (--) into an underscore (_). header_key = header_key.replace('_', '--') headers[header_key] = value # Parse the prepared metadata into HTTP headers, # and add them to the ``headers`` dict. _prepare_metadata_headers(prepared_metadata) _prepare_metadata_headers(prepared_file_metadata, meta_type='filemeta') super().prepare_headers(headers) class MetadataRequest(requests.models.Request): def __init__(self, metadata=None, source_metadata=None, target=None, priority=None, access_key=None, secret_key=None, append=None, expect=None, append_list=None, insert=None, **kwargs): super().__init__(**kwargs) if not self.auth: self.auth = auth.S3PostAuth(access_key, secret_key) metadata = metadata or {} self.metadata = metadata self.source_metadata = source_metadata self.target = target self.priority = priority self.append = append self.expect = expect self.append_list = append_list self.insert = insert def prepare(self): p = MetadataPreparedRequest() p.prepare( method=self.method, url=self.url, headers=self.headers, files=self.files, data=self.data, params=self.params, auth=self.auth, cookies=self.cookies, hooks=self.hooks, # MetadataRequest kwargs. metadata=self.metadata, priority=self.priority, source_metadata=self.source_metadata, target=self.target, append=self.append, expect=self.expect, append_list=self.append_list, insert=self.insert, ) return p class MetadataPreparedRequest(requests.models.PreparedRequest): def prepare(self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, metadata={}, # noqa: B006 source_metadata=None, target=None, priority=None, append=None, expect=None, append_list=None, insert=None): self.prepare_method(method) self.prepare_url(url, params) self.identifier = self.url.split("?")[0].split("/")[-1] self.prepare_headers(headers) self.prepare_cookies(cookies) self.prepare_body(metadata, source_metadata, target, priority, append, append_list, insert, expect) self.prepare_auth(auth, url) # Note that prepare_auth must be last to enable authentication schemes # such as OAuth to work on a fully prepared request. # This MUST go after prepare_auth. Authenticators could add a hook self.prepare_hooks(hooks) def prepare_body(self, metadata, source_metadata, target, priority, append, append_list, insert, expect): priority = priority or -5 if not source_metadata: r = requests.get(self.url, timeout=10) source_metadata = r.json() # Write to many targets if (isinstance(metadata, list) or any('/' in k for k in metadata) or all(isinstance(k, dict) for k in metadata.values())): changes = [] if any(not k for k in metadata): raise ValueError('Invalid metadata provided, ' 'check your input and try again') if target: metadata = {target: metadata} for key in metadata: if key == 'metadata': try: patch = prepare_patch(metadata[key], source_metadata['metadata'], append, expect, append_list, insert) except KeyError: raise ItemLocateError(f"{self.identifier} cannot be located " "because it is dark or does not exist.") elif key.startswith('files'): patch = prepare_files_patch(metadata[key], source_metadata['files'], append, key, append_list, insert, expect) else: key = key.split('/')[0] patch = prepare_target_patch(metadata, source_metadata, append, target, append_list, key, insert, expect) changes.append({'target': key, 'patch': patch}) self.data = { '-changes': json.dumps(changes), 'priority': priority, } logger.debug(f'submitting metadata request: {self.data}') # Write to single target else: if not target or 'metadata' in target: target = 'metadata' try: patch = prepare_patch(metadata, source_metadata['metadata'], append, expect, append_list, insert) except KeyError: raise ItemLocateError(f"{self.identifier} cannot be located " "because it is dark or does not exist.") elif 'files' in target: patch = prepare_files_patch(metadata, source_metadata['files'], append, target, append_list, insert, expect) else: metadata = {target: metadata} patch = prepare_target_patch(metadata, source_metadata, append, target, append_list, target, insert, expect) self.data = { '-patch': json.dumps(patch), '-target': target, 'priority': priority, } logger.debug(f'submitting metadata request: {self.data}') super().prepare_body(self.data, None) def prepare_patch(metadata, source_metadata, append, expect=None, append_list=None, insert=None): destination_metadata = source_metadata.copy() if isinstance(metadata, list): prepared_metadata = metadata if not destination_metadata: destination_metadata = [] else: prepared_metadata = prepare_metadata(metadata, source_metadata, append, append_list, insert) if isinstance(destination_metadata, dict): destination_metadata.update(prepared_metadata) elif isinstance(metadata, list) and not destination_metadata: destination_metadata = metadata else: if isinstance(prepared_metadata, list): if append_list: destination_metadata += prepared_metadata else: destination_metadata = prepared_metadata else: destination_metadata.append(prepared_metadata) # Delete metadata items where value is REMOVE_TAG. destination_metadata = delete_items_from_dict(destination_metadata, 'REMOVE_TAG') patch = make_patch(source_metadata, destination_metadata).patch # Add test operations to patch. patch_tests = [] for expect_key in expect: idx = None if '[' in expect_key: idx = int(expect_key.split('[')[1].strip(']')) key = expect_key.split('[')[0] path = f'/{key}/{idx}' p_test = {'op': 'test', 'path': path, 'value': expect[expect_key]} else: path = f'/{expect_key}' p_test = {'op': 'test', 'path': path, 'value': expect[expect_key]} patch_tests.append(p_test) final_patch = patch_tests + patch return final_patch def prepare_target_patch(metadata, source_metadata, append, target, append_list, key, insert, expect): def dictify(lst, key=None, value=None): if not lst: return value sub_dict = dictify(lst[1:], key, value) for v in lst: md = {v: copy.deepcopy(sub_dict)} return md for _k in metadata: metadata = dictify(_k.split('/')[1:], _k.split('/')[-1], metadata[_k]) for i, _k in enumerate(key.split('/')): if i == 0: source_metadata = source_metadata.get(_k, {}) else: source_metadata[_k] = source_metadata.get(_k, {}).get(_k, {}) patch = prepare_patch(metadata, source_metadata, append, expect, append_list, insert) return patch def prepare_files_patch(metadata, source_metadata, append, target, append_list, insert, expect): filename = '/'.join(target.split('/')[1:]) for f in source_metadata: if f.get('name') == filename: source_metadata = f break patch = prepare_patch(metadata, source_metadata, append, expect, append_list, insert) return patch def prepare_metadata(metadata, source_metadata=None, append=False, append_list=False, insert=False): """Prepare a metadata dict for an :class:`S3PreparedRequest <S3PreparedRequest>` or :class:`MetadataPreparedRequest <MetadataPreparedRequest>` object. :type metadata: dict :param metadata: The metadata dict to be prepared. :type source_metadata: dict :param source_metadata: (optional) The source metadata for the item being modified. :rtype: dict :returns: A filtered metadata dict to be used for generating IA S3 and Metadata API requests. """ # Make a deepcopy of source_metadata if it exists. A deepcopy is # necessary to avoid modifying the original dict. source_metadata = {} if not source_metadata else copy.deepcopy(source_metadata) prepared_metadata = {} # Functions for dealing with metadata keys containing indexes. def get_index(key): match = re.search(r'(?<=\[)\d+(?=\])', key) if match is not None: return int(match.group()) def rm_index(key): return key.split('[')[0] # Create indexed_keys counter dict. i.e.: {'subject': 3} -- subject # (with the index removed) appears 3 times in the metadata dict. indexed_keys = {} for key in metadata: # Convert number values to strings! if isinstance(metadata[key], (int, float, complex)): metadata[key] = str(metadata[key]) if get_index(key) is None: continue count = len([x for x in metadata if rm_index(x) == rm_index(key)]) indexed_keys[rm_index(key)] = count # Initialize the values for all indexed_keys. for key in indexed_keys: # Increment the counter so we know how many values the final # value in prepared_metadata should have. indexed_keys[key] += len(source_metadata.get(key, [])) # Initialize the value in the prepared_metadata dict. prepared_metadata[key] = source_metadata.get(key, []) if not isinstance(prepared_metadata[key], list): prepared_metadata[key] = [prepared_metadata[key]] # Fill the value of the prepared_metadata key with None values # so all indexed items can be indexed in order. while len(prepared_metadata[key]) < indexed_keys[key]: prepared_metadata[key].append(None) # Index all items which contain an index. for key in metadata: # Insert values from indexed keys into prepared_metadata dict. if (rm_index(key) in indexed_keys) and not insert: try: prepared_metadata[rm_index(key)][get_index(key)] = metadata[key] except IndexError: prepared_metadata[rm_index(key)].append(metadata[key]) # If append is True, append value to source_metadata value. elif append_list and source_metadata.get(key): if not isinstance(metadata[key], list): metadata[key] = [metadata[key]] for v in metadata[key]: if not isinstance(source_metadata[key], list): if v in [source_metadata[key]]: continue else: if v in source_metadata[key]: source_metadata[key] = [x for x in source_metadata[key] if x != v] if not isinstance(source_metadata[key], list): prepared_metadata[key] = [source_metadata[key]] else: prepared_metadata[key] = source_metadata[key] prepared_metadata[key].append(v) elif append and source_metadata.get(key): prepared_metadata[key] = f'{source_metadata[key]} {metadata[key]}' elif insert and source_metadata.get(rm_index(key)): index = get_index(key) # If no index is provided, e.g. `collection[i]`, assume 0 if not index: index = 0 _key = rm_index(key) if not isinstance(source_metadata[_key], list): source_metadata[_key] = [source_metadata[_key]] source_metadata[_key].insert(index, metadata[key]) insert_md = [] for _v in source_metadata[_key]: if _v not in insert_md and _v: insert_md.append(_v) prepared_metadata[_key] = insert_md else: prepared_metadata[key] = metadata[key] # Remove values from metadata if value is REMOVE_TAG. _done = [] for key in indexed_keys: # Filter None values from items with arrays as values prepared_metadata[key] = [v for v in prepared_metadata[key] if v] # Only filter the given indexed key if it has not already been # filtered. if key not in _done: indexes = [] for k in metadata: if not get_index(k): continue elif rm_index(k) != key: continue elif metadata[k] != 'REMOVE_TAG': continue else: indexes.append(get_index(k)) # Delete indexed values in reverse to not throw off the # subsequent indexes. for i in sorted(indexes, reverse=True): del prepared_metadata[key][i] _done.append(key) return prepared_metadata
21,154
Python
.py
461
32.798265
92
0.566823
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,408
search.py
jjjake_internetarchive/internetarchive/search.py
# # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2019 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ internetarchive.search ~~~~~~~~~~~~~~~~~~~~~~ This module provides objects for interacting with the Archive.org search engine. :copyright: (C) 2012-2019 by Internet Archive. :license: AGPL 3, see LICENSE for more details. """ import itertools from logging import getLogger from requests.exceptions import ReadTimeout from internetarchive.auth import S3Auth log = getLogger(__name__) class Search: """This class represents an archive.org item search. You can use this class to search for Archive.org items using the advanced search engine. Usage:: >>> from internetarchive.session import ArchiveSession >>> from internetarchive.search import Search >>> s = ArchiveSession() >>> search = Search(s, '(uploader:jake@archive.org)') >>> for result in search: ... print(result['identifier']) """ def __init__(self, archive_session, query, fields=None, sorts=None, params=None, full_text_search=None, dsl_fts=None, request_kwargs=None, max_retries=None): params = params or {} self.session = archive_session self.dsl_fts = False if not dsl_fts else True if self.dsl_fts or full_text_search: self.fts = True else: self.fts = False self.query = query if self.fts and not self.dsl_fts: self.query = f'!L {self.query}' self.fields = fields or [] self.sorts = sorts or [] self.request_kwargs = request_kwargs or {} self._num_found = None self.fts_url = f'{self.session.protocol}//be-api.us.archive.org/ia-pub-fts-api' self.scrape_url = f'{self.session.protocol}//{self.session.host}/services/search/v1/scrape' self.search_url = f'{self.session.protocol}//{self.session.host}/advancedsearch.php' if self.session.access_key and self.session.secret_key: self.auth = S3Auth(self.session.access_key, self.session.secret_key) else: self.auth = None self.max_retries = max_retries if max_retries is not None else 5 # Initialize params. default_params = {'q': self.query} if 'page' not in params: if 'rows' in params: params['page'] = 1 else: default_params['count'] = 10000 else: default_params['output'] = 'json' # In the beta endpoint 'scope' was called 'index'. # Let's support both for a while. if 'index' in params: params['scope'] = params['index'] del params['index'] self.params = default_params.copy() self.params.update(params) # Set timeout. if 'timeout' not in self.request_kwargs: self.request_kwargs['timeout'] = 300 # Set retries. self.session.mount_http_adapter(max_retries=self.max_retries) def __repr__(self): return f'Search(query={self.query!r})' def __iter__(self): return self.iter_as_results() def _advanced_search(self): # Always return identifier. if 'identifier' not in self.fields: self.fields.append('identifier') for k, v in enumerate(self.fields): self.params[f'fl[{k}]'] = v for i, field in enumerate(self.sorts): self.params[f'sort[{i}]'] = field self.params['output'] = 'json' r = self.session.get(self.search_url, params=self.params, auth=self.auth, **self.request_kwargs) j = r.json() num_found = int(j.get('response', {}).get('numFound', 0)) if not self._num_found: self._num_found = num_found if j.get('error'): yield j yield from j.get('response', {}).get('docs', []) def _scrape(self): if self.fields: self.params['fields'] = ','.join(self.fields) if self.sorts: self.params['sorts'] = ','.join(self.sorts) i = 0 num_found = None while True: r = self.session.post(self.scrape_url, params=self.params, auth=self.auth, **self.request_kwargs) j = r.json() if j.get('error'): yield j if not num_found: num_found = int(j.get('total') or '0') if not self._num_found: self._num_found = num_found self._handle_scrape_error(j) self.params['cursor'] = j.get('cursor') for item in j['items']: i += 1 yield item if 'cursor' not in j: if i != num_found: raise ReadTimeout('The server failed to return results in the' f' allotted amount of time for {r.request.url}') break def _full_text_search(self): d = { 'q': self.query, 'size': '10000', 'from': '0', 'scroll': 'true', } if 'scope' in self.params: d['scope'] = self.params['scope'] if 'size' in self.params: d['scroll'] = False d['size'] = self.params['size'] while True: r = self.session.post(self.fts_url, json=d, auth=self.auth, **self.request_kwargs) j = r.json() scroll_id = j.get('_scroll_id') hits = j.get('hits', {}).get('hits') if not hits: return yield from hits if not hits or d['scroll'] is False: break d['scroll_id'] = scroll_id def _make_results_generator(self): if self.fts: return self._full_text_search() if 'user_aggs' in self.params: return self._user_aggs() elif 'page' in self.params: return self._advanced_search() else: return self._scrape() def _user_aggs(self): """Experimental support for user aggregations. """ self.params['page'] = '1' self.params['rows'] = '1' self.params['output'] = 'json' r = self.session.get(self.search_url, params=self.params, auth=self.auth, **self.request_kwargs) j = r.json() if j.get('error'): yield j for agg in j.get('response', {}).get('aggregations', {}).items(): yield {agg[0]: agg[1]} @property def num_found(self): if not self._num_found: if not self.fts: p = self.params.copy() p['total_only'] = 'true' r = self.session.post(self.scrape_url, params=p, auth=self.auth, **self.request_kwargs) j = r.json() self._handle_scrape_error(j) self._num_found = j.get('total') else: self.params['q'] = self.query r = self.session.get(self.fts_url, params=self.params, auth=self.auth, **self.request_kwargs) j = r.json() self._num_found = j.get('hits', {}).get('total') return self._num_found def _handle_scrape_error(self, j): if 'error' in j: if all(s in j['error'].lower() for s in ['invalid', 'secret']): if not j['error'].endswith('.'): j['error'] += '.' raise ValueError(f"{j['error']} Try running 'ia configure' and retrying.") raise ValueError(j.get('error')) def _get_item_from_search_result(self, search_result): return self.session.get_item(search_result['identifier']) def iter_as_results(self): return SearchIterator(self, self._make_results_generator()) def iter_as_items(self): _map = map(self._get_item_from_search_result, self._make_results_generator()) return SearchIterator(self, _map) def __len__(self): return self.num_found class SearchIterator: """This class is an iterator wrapper for search results. It provides access to the underlying Search, and supports len() (since that is known initially).""" def __init__(self, search, iterator): self.search = search self.iterator = iterator def __len__(self): return self.search.num_found def __next__(self): return next(self.iterator) def __iter__(self): return self def __repr__(self): return f'{self.__class__.__name__}({self.search!r}, {self.iterator!r})'
9,958
Python
.py
249
28.409639
99
0.538279
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,409
api.py
jjjake_internetarchive/internetarchive/api.py
# # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2019 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ internetarchive.api ~~~~~~~~~~~~~~~~~~~ This module implements the Internetarchive API. :copyright: (C) 2012-2019 by Internet Archive. :license: AGPL 3, see LICENSE for more details. """ from __future__ import annotations from getpass import getpass from typing import Iterable, Mapping, MutableMapping import requests from urllib3 import Retry from internetarchive import auth, catalog, files, item, search, session from internetarchive import config as config_module from internetarchive.exceptions import AuthenticationError def get_session( config: Mapping | None = None, config_file: str | None = None, debug: bool = False, http_adapter_kwargs: MutableMapping | None = None, ) -> session.ArchiveSession: """Return a new :class:`ArchiveSession` object. The :class:`ArchiveSession` object is the main interface to the ``internetarchive`` lib. It allows you to persist certain parameters across tasks. :param config: A dictionary used to configure your session. :param config_file: A path to a config file used to configure your session. :param debug: To be passed on to this session's method calls. :param http_adapter_kwargs: Keyword arguments that :py:class:`requests.adapters.HTTPAdapter` takes. :returns: To persist certain parameters across tasks. Usage: >>> from internetarchive import get_session >>> config = {'s3': {'access': 'foo', 'secret': 'bar'}} >>> s = get_session(config) >>> s.access_key 'foo' From the session object, you can access all of the functionality of the ``internetarchive`` lib: >>> item = s.get_item('nasa') >>> item.download() nasa: ddddddd - success >>> s.get_tasks(task_ids=31643513)[0].server 'ia311234' """ return session.ArchiveSession(config, config_file or "", debug, http_adapter_kwargs) def get_item( identifier: str, config: Mapping | None = None, config_file: str | None = None, archive_session: session.ArchiveSession | None = None, debug: bool = False, http_adapter_kwargs: MutableMapping | None = None, request_kwargs: MutableMapping | None = None, ) -> item.Item: """Get an :class:`Item` object. :param identifier: The globally unique Archive.org item identifier. :param config: A dictionary used to configure your session. :param config_file: A path to a config file used to configure your session. :param archive_session: An :class:`ArchiveSession` object can be provided via the ``archive_session`` parameter. :param debug: To be passed on to get_session(). :param http_adapter_kwargs: Keyword arguments that :py:class:`requests.adapters.HTTPAdapter` takes. :param request_kwargs: Keyword arguments that :py:class:`requests.Request` takes. :returns: The Item that fits the criteria. Usage: >>> from internetarchive import get_item >>> item = get_item('nasa') >>> item.item_size 121084 """ if not archive_session: archive_session = get_session(config, config_file, debug, http_adapter_kwargs) return archive_session.get_item(identifier, request_kwargs=request_kwargs) def get_files( identifier: str, files: files.File | list[files.File] | None = None, formats: str | list[str] | None = None, glob_pattern: str | None = None, exclude_pattern: str | None = None, on_the_fly: bool = False, **get_item_kwargs, ) -> list[files.File]: r"""Get :class:`File` objects from an item. :param identifier: The globally unique Archive.org identifier for a given item. :param files: Only return files matching the given filenames. :param formats: Only return files matching the given formats. :param glob_pattern: Only return files matching the given glob pattern. :param exclude_pattern: Exclude files matching the given glob pattern. :param on_the_fly: Include on-the-fly files (i.e. derivative EPUB, MOBI, DAISY files). :param \*\*get_item_kwargs: Arguments that ``get_item()`` takes. :returns: Files from an item. Usage: >>> from internetarchive import get_files >>> fnames = [f.name for f in get_files('nasa', glob_pattern='*xml')] >>> print(fnames) ['nasa_reviews.xml', 'nasa_meta.xml', 'nasa_files.xml'] """ item = get_item(identifier, **get_item_kwargs) return item.get_files(files, formats, glob_pattern, exclude_pattern, on_the_fly) def modify_metadata( identifier: str, metadata: Mapping, target: str | None = None, append: bool = False, append_list: bool = False, priority: int = 0, access_key: str | None = None, secret_key: str | None = None, debug: bool = False, request_kwargs: Mapping | None = None, **get_item_kwargs, ) -> requests.Request | requests.Response: r"""Modify the metadata of an existing item on Archive.org. :param identifier: The globally unique Archive.org identifier for a given item. :param metadata: Metadata used to update the item. :param target: The metadata target to update. Defaults to `metadata`. :param append: set to True to append metadata values to current values rather than replacing. Defaults to ``False``. :param append_list: Append values to an existing multi-value metadata field. No duplicate values will be added. :param priority: Set task priority. :param access_key: IA-S3 access_key to use when making the given request. :param secret_key: IA-S3 secret_key to use when making the given request. :param debug: set to True to return a :class:`requests.Request <Request>` object instead of sending request. Defaults to ``False``. :param \*\*get_item_kwargs: Arguments that ``get_item`` takes. :returns: A Request if debug else a Response. """ item = get_item(identifier, **get_item_kwargs) return item.modify_metadata( metadata, target=target, append=append, append_list=append_list, priority=priority, access_key=access_key, secret_key=secret_key, debug=debug, request_kwargs=request_kwargs, refresh=False ) def upload( identifier: str, files, metadata: Mapping | None = None, headers: dict | None = None, access_key: str | None = None, secret_key: str | None = None, queue_derive=None, verbose: bool = False, verify: bool = False, checksum: bool = False, delete: bool = False, retries: int | None = None, retries_sleep: int | None = None, debug: bool = False, validate_identifier: bool = False, request_kwargs: dict | None = None, **get_item_kwargs, ) -> list[requests.Request | requests.Response]: r"""Upload files to an item. The item will be created if it does not exist. :param identifier: The globally unique Archive.org identifier for a given item. :param files: The filepaths or file-like objects to upload. This value can be an iterable or a single file-like object or string. :param metadata: Metadata used to create a new item. If the item already exists, the metadata will not be updated -- use ``modify_metadata``. :param headers: Add additional HTTP headers to the request. :param access_key: IA-S3 access_key to use when making the given request. :param secret_key: IA-S3 secret_key to use when making the given request. :param queue_derive: Set to False to prevent an item from being derived after upload. :param verbose: Display upload progress. :param verify: Verify local MD5 checksum matches the MD5 checksum of the file received by IAS3. :param checksum: Skip uploading files based on checksum. :param delete: Delete local file after the upload has been successfully verified. :param retries: Number of times to retry the given request if S3 returns a 503 SlowDown error. :param retries_sleep: Amount of time to sleep between ``retries``. :param debug: Set to True to print headers to stdout, and exit without sending the upload request. :param validate_identifier: Set to True to validate the identifier before uploading the file. :param \*\*kwargs: Optional arguments that ``get_item`` takes. :returns: A list Requests if debug else a list of Responses. """ item = get_item(identifier, **get_item_kwargs) return item.upload( files, metadata=metadata, headers=headers, access_key=access_key, secret_key=secret_key, queue_derive=queue_derive, verbose=verbose, verify=verify, checksum=checksum, delete=delete, retries=retries, retries_sleep=retries_sleep, debug=debug, validate_identifier=validate_identifier, request_kwargs=request_kwargs, ) def download( identifier: str, files: files.File | list[files.File] | None = None, formats: str | list[str] | None = None, glob_pattern: str | None = None, dry_run: bool = False, verbose: bool = False, ignore_existing: bool = False, checksum: bool = False, checksum_archive: bool = False, destdir: str | None = None, no_directory: bool = False, retries: int | None = None, item_index: int | None = None, ignore_errors: bool = False, on_the_fly: bool = False, return_responses: bool = False, no_change_timestamp: bool = False, timeout: int | float | tuple[int, float] | None = None, **get_item_kwargs, ) -> list[requests.Request | requests.Response]: r"""Download files from an item. :param identifier: The globally unique Archive.org identifier for a given item. :param files: Only return files matching the given file names. :param formats: Only return files matching the given formats. :param glob_pattern: Only return files matching the given glob pattern. :param dry_run: Print URLs to files to stdout rather than downloading them. :param verbose: Turn on verbose output. :param ignore_existing: Skip files that already exist locally. :param checksum: Skip downloading file based on checksum. :param checksum_archive: Skip downloading file based on checksum, and skip checksum validation if it already succeeded (will create and use _checksum_archive.txt). :param destdir: The directory to download files to. :param no_directory: Download files to current working directory rather than creating an item directory. :param retries: The number of times to retry on failed requests. :param item_index: The index of the item for displaying progress in bulk downloads. :param ignore_errors: Don't fail if a single file fails to download, continue to download other files. :param on_the_fly: Download on-the-fly files (i.e. derivative EPUB, MOBI, DAISY files). :param return_responses: Rather than downloading files to disk, return a list of response objects. :param \*\*kwargs: Optional arguments that ``get_item`` takes. :returns: A list Requests if debug else a list of Responses. """ item = get_item(identifier, **get_item_kwargs) r = item.download( files=files, formats=formats, glob_pattern=glob_pattern, dry_run=dry_run, verbose=verbose, ignore_existing=ignore_existing, checksum=checksum, checksum_archive=checksum_archive, destdir=destdir, no_directory=no_directory, retries=retries, item_index=item_index, ignore_errors=ignore_errors, on_the_fly=on_the_fly, return_responses=return_responses, no_change_timestamp=no_change_timestamp, timeout=timeout, ) return r def delete( identifier: str, files: files.File | list[files.File] | None = None, formats: str | list[str] | None = None, glob_pattern: str | None = None, cascade_delete: bool = False, access_key: str | None = None, secret_key: str | None = None, verbose: bool = False, debug: bool = False, **kwargs, ) -> list[requests.Request | requests.Response]: """Delete files from an item. Note: Some system files, such as <itemname>_meta.xml, cannot be deleted. :param identifier: The globally unique Archive.org identifier for a given item. :param files: Only return files matching the given filenames. :param formats: Only return files matching the given formats. :param glob_pattern: Only return files matching the given glob pattern. :param cascade_delete: Delete all files associated with the specified file, including upstream derivatives and the original. :param access_key: IA-S3 access_key to use when making the given request. :param secret_key: IA-S3 secret_key to use when making the given request. :param verbose: Print actions to stdout. :param debug: Set to True to print headers to stdout and exit exit without sending the delete request. :returns: A list Requests if debug else a list of Responses """ _files = get_files(identifier, files, formats, glob_pattern, **kwargs) responses = [] for f in _files: r = f.delete( cascade_delete=cascade_delete, access_key=access_key, secret_key=secret_key, verbose=verbose, debug=debug, ) responses.append(r) return responses def get_tasks( identifier: str = "", params: dict | None = None, config: Mapping | None = None, config_file: str | None = None, archive_session: session.ArchiveSession | None = None, http_adapter_kwargs: MutableMapping | None = None, request_kwargs: MutableMapping | None = None, ) -> set[catalog.CatalogTask]: """Get tasks from the Archive.org catalog. :param identifier: The Archive.org identifier for which to retrieve tasks for. :param params: The URL parameters to send with each request sent to the Archive.org catalog API. :returns: A set of :class:`CatalogTask` objects. """ if not archive_session: archive_session = get_session(config, config_file, False, http_adapter_kwargs) return archive_session.get_tasks( identifier=identifier, params=params, request_kwargs=request_kwargs ) def search_items( query: str, fields: Iterable | None = None, sorts=None, params: Mapping | None = None, full_text_search: bool = False, dsl_fts: bool = False, archive_session: session.ArchiveSession | None = None, config: Mapping | None = None, config_file: str | None = None, http_adapter_kwargs: MutableMapping | None = None, request_kwargs: Mapping | None = None, max_retries: int | Retry | None = None, ) -> search.Search: """Search for items on Archive.org. :param query: The Archive.org search query to yield results for. Refer to https://archive.org/advancedsearch.php#raw for help formatting your query. :param fields: The metadata fields to return in the search results. :param params: The URL parameters to send with each request sent to the Archive.org Advancedsearch Api. :param full_text_search: Beta support for querying the archive.org Full Text Search API [default: False]. :param dsl_fts: Beta support for querying the archive.org Full Text Search API in dsl (i.e. do not prepend ``!L `` to the ``full_text_search`` query [default: False]. :param secure: Configuration options for session. :param config_file: A path to a config file used to configure your session. :param http_adapter_kwargs: Keyword arguments that :py:class:`requests.adapters.HTTPAdapter` takes. :param request_kwargs: Keyword arguments that :py:class:`requests.Request` takes. :param max_retries: The number of times to retry a failed request. This can also be an `urllib3.Retry` object. If you need more control (e.g. `status_forcelist`), use a `ArchiveSession` object, and mount your own adapter after the session object has been initialized. For example:: >>> s = get_session() >>> s.mount_http_adapter() >>> search_results = s.search_items('nasa') See :meth:`ArchiveSession.mount_http_adapter` for more details. :returns: A :class:`Search` object, yielding search results. """ if not archive_session: archive_session = get_session(config, config_file, False, http_adapter_kwargs) return archive_session.search_items( query, fields=fields, sorts=sorts, params=params, full_text_search=full_text_search, dsl_fts=dsl_fts, request_kwargs=request_kwargs, max_retries=max_retries, ) def configure( # nosec: hardcoded_password_default username: str = "", password: str = "", config_file: str = "", host: str = "archive.org", ) -> str: """Configure internetarchive with your Archive.org credentials. :param username: The email address associated with your Archive.org account. :param password: Your Archive.org password. :returns: The config file path. Usage: >>> from internetarchive import configure >>> configure('user@example.com', 'password') """ auth_config = config_module.get_auth_config( username or input("Email address: "), password or getpass("Password: "), host, ) config_file_path = config_module.write_config_file(auth_config, config_file) return config_file_path def get_username(access_key: str, secret_key: str) -> str: """Returns an Archive.org username given an IA-S3 key pair. :param access_key: IA-S3 access_key to use when making the given request. :param secret_key: IA-S3 secret_key to use when making the given request. :returns: The username. """ j = get_user_info(access_key, secret_key) return j.get("username", "") def get_user_info(access_key: str, secret_key: str) -> dict[str, str]: """Returns details about an Archive.org user given an IA-S3 key pair. :param access_key: IA-S3 access_key to use when making the given request. :param secret_key: IA-S3 secret_key to use when making the given request. :returns: Archive.org use info. """ u = "https://s3.us.archive.org" p = {"check_auth": 1} r = requests.get(u, params=p, auth=auth.S3Auth(access_key, secret_key), timeout=10) r.raise_for_status() j = r.json() if j.get("error"): raise AuthenticationError(j.get("error")) else: return j
20,362
Python
.py
455
37.171429
89
0.662367
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,410
auth.py
jjjake_internetarchive/internetarchive/auth.py
# # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2019 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ internetarchive.auth ~~~~~~~~~~~~~~~~~~~~ This module contains the Archive.org authentication handlers for Requests. :copyright: (C) 2012-2019 by Internet Archive. :license: AGPL 3, see LICENSE for more details. """ from __future__ import annotations from requests.auth import AuthBase from internetarchive.exceptions import AuthenticationError class S3Auth(AuthBase): """Attaches S3 Basic Authentication to the given Request object.""" def __init__(self, access_key: str | None = None, secret_key: str | None = None): self.access_key = access_key self.secret_key = secret_key def __call__(self, r): if not self.access_key: if self.secret_key: raise AuthenticationError('No access_key set!' ' Have you run `ia configure`?') if not self.secret_key: if self.access_key: raise AuthenticationError('No secret_key set!' ' Have you run `ia configure`?') else: raise AuthenticationError('No access_key or secret_key set!' ' Have you run `ia configure`?') auth_str = f'LOW {self.access_key}:{self.secret_key}' r.headers['Authorization'] = auth_str return r class S3PostAuth(AuthBase): """Attaches S3 Basic Authentication to the given Request object.""" def __init__(self, access_key: str | None = None, secret_key: str | None = None): self.access_key = access_key self.secret_key = secret_key def __call__(self, r): auth_str = f'&access={self.access_key}&secret={self.secret_key}' if not r.body: r.body = '' r.body += auth_str r.headers['content-type'] = 'application/x-www-form-urlencoded' return r
2,641
Python
.py
59
37.491525
85
0.652529
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,411
utils.py
jjjake_internetarchive/internetarchive/utils.py
# # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2022 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ internetarchive.utils ~~~~~~~~~~~~~~~~~~~~~ This module provides utility functions for the internetarchive library. :copyright: (C) 2012-2022 by Internet Archive. :license: AGPL 3, see LICENSE for more details. """ from __future__ import annotations import hashlib import os import re import sys from collections.abc import Mapping from typing import Iterable from xml.dom.minidom import parseString # Make preferred JSON package available via `from internetarchive.utils import json` try: import ujson as json # ujson lacks a JSONDecodeError: https://github.com/ultrajson/ultrajson/issues/497 JSONDecodeError = ValueError except ImportError: import json # type: ignore JSONDecodeError = json.JSONDecodeError # type: ignore def deep_update(d: dict, u: Mapping) -> dict: for k, v in u.items(): if isinstance(v, Mapping): r = deep_update(d.get(k, {}), v) d[k] = r else: d[k] = u[k] return d class InvalidIdentifierException(Exception): pass def validate_s3_identifier(string: str) -> bool: legal_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-' # periods, underscores, and dashes are legal, but may not be the first # character! if any(string.startswith(c) is True for c in ['.', '_', '-']): raise InvalidIdentifierException('Identifier cannot begin with periods ".", underscores ' '"_", or dashes "-".') if len(string) > 100 or len(string) < 3: raise InvalidIdentifierException('Identifier should be between 3 and 80 characters in ' 'length.') # Support for uploading to user items, e.g. first character can be `@`. if string.startswith('@'): string = string[1:] if any(c not in legal_chars for c in string): raise InvalidIdentifierException('Identifier can only contain alphanumeric characters, ' 'periods ".", underscores "_", or dashes "-". However, ' 'identifier cannot begin with periods, underscores, or ' 'dashes.') return True def needs_quote(s: str) -> bool: try: s.encode('ascii') except (UnicodeDecodeError, UnicodeEncodeError): return True return re.search(r'\s', s) is not None def norm_filepath(fp: bytes | str) -> str: if isinstance(fp, bytes): fp = fp.decode('utf-8') fp = fp.replace(os.path.sep, '/') if not fp.startswith('/'): fp = f'/{fp}' return fp def get_md5(file_object) -> str: m = hashlib.md5() while True: data = file_object.read(8192) if not data: break m.update(data) file_object.seek(0, os.SEEK_SET) return m.hexdigest() def chunk_generator(fp, chunk_size: int): while True: chunk = fp.read(chunk_size) if not chunk: break yield chunk def suppress_keyboard_interrupt_message() -> None: """Register a new excepthook to suppress KeyboardInterrupt exception messages, and exit with status code 130. """ old_excepthook = sys.excepthook def new_hook(type, value, traceback): if type != KeyboardInterrupt: old_excepthook(type, value, traceback) else: sys.exit(130) sys.excepthook = new_hook class IterableToFileAdapter: def __init__(self, iterable, size: int, pre_encode: bool = False): self.iterator = iter(iterable) self.length = size # pre_encode is needed because http doesn't know that it # needs to encode a TextIO object when it's wrapped # in the Iterator from tqdm. # So, this FileAdapter provides pre-encoded output self.pre_encode = pre_encode def read(self, size: int = -1): # TBD: add buffer for `len(data) > size` case if self.pre_encode: # this adapter is intended to emulate the encoding that is usually # done by the http lib. # As of 2022, iso-8859-1 encoding is used to meet the HTTP standard, # see in the cpython repo (https://github.com/python/cpython # Lib/http/client.py lines 246; 1340; or grep 'iso-8859-1' return next(self.iterator, '').encode("iso-8859-1") return next(self.iterator, b'') def __len__(self) -> int: return self.length class IdentifierListAsItems: """This class is a lazily-loaded list of Items, accessible by index or identifier. """ def __init__(self, id_list_or_single_id, session): self.ids = (id_list_or_single_id if isinstance(id_list_or_single_id, list) else [id_list_or_single_id]) self._items = [None] * len(self.ids) self.session = session def __len__(self) -> int: return len(self.ids) def __getitem__(self, idx): for i in (range(*idx.indices(len(self))) if isinstance(idx, slice) else [idx]): if self._items[i] is None: self._items[i] = self.session.get_item(self.ids[i]) return self._items[idx] def __getattr__(self, name): try: return self[self.ids.index(name)] except ValueError: raise AttributeError def __repr__(self) -> str: return f'{self.__class__.__name__}({self.ids!r})' def get_s3_xml_text(xml_str: str) -> str: def _get_tag_text(tag_name, xml_obj): text = '' elements = xml_obj.getElementsByTagName(tag_name) for e in elements: for node in e.childNodes: if node.nodeType == node.TEXT_NODE: text += node.data return text tag_names = ['Message', 'Resource'] try: p = parseString(xml_str) _msg = _get_tag_text('Message', p) _resource = _get_tag_text('Resource', p) # Avoid weird Resource text that contains PUT method. if _resource and "'PUT" not in _resource: return f'{_msg} - {_resource.strip()}' else: return _msg except Exception: return str(xml_str) def get_file_size(file_obj) -> int | None: if is_filelike_obj(file_obj): try: file_obj.seek(0, os.SEEK_END) size = file_obj.tell() # Avoid OverflowError. if size > sys.maxsize: size = None file_obj.seek(0, os.SEEK_SET) except OSError: size = None else: st = os.stat(file_obj) size = st.st_size return size def iter_directory(directory: str): """Given a directory, yield all files recursively as a two-tuple (filepath, s3key)""" for path, _dir, files in os.walk(directory): for f in files: filepath = os.path.join(path, f) key = os.path.relpath(filepath, directory) yield (filepath, key) def recursive_file_count_and_size(files, item=None, checksum=False): """Given a filepath or list of filepaths, return the total number and size of files. If `checksum` is `True`, skip over files whose MD5 hash matches any file in the `item`. """ if not isinstance(files, (list, set)): files = [files] total_files = 0 total_size = 0 if checksum is True: md5s = [f.get('md5') for f in item.files] else: md5s = [] if isinstance(files, dict): # make sure to use local filenames. _files = files.values() else: if isinstance(files[0], tuple): _files = dict(files).values() else: _files = files for f in _files: try: is_dir = os.path.isdir(f) except TypeError: try: f = f[0] is_dir = os.path.isdir(f) except (AttributeError, TypeError): is_dir = False if is_dir: it = iter_directory(f) else: it = [(f, None)] for x, _ in it: if checksum is True: try: with open(x, 'rb') as fh: lmd5 = get_md5(fh) except TypeError: # Support file-like objects. lmd5 = get_md5(x) if lmd5 in md5s: continue total_size += get_file_size(x) total_files += 1 return total_files, total_size def recursive_file_count(*args, **kwargs): """Like `recursive_file_count_and_size`, but returns only the file count.""" total_files, _ = recursive_file_count_and_size(*args, **kwargs) return total_files def is_dir(obj) -> bool: """Special is_dir function to handle file-like object cases that cannot be stat'd""" try: return os.path.isdir(obj) except TypeError as exc: return False def is_filelike_obj(obj) -> bool: """Distinguish file-like from path-like objects""" try: os.fspath(obj) except TypeError: return True else: return False def reraise_modify( caught_exc: Exception, append_msg: str, prepend: bool = False, ) -> None: """Append message to exception while preserving attributes. Preserves exception class, and exception traceback. Note: This function needs to be called inside an except because an exception must be active in the current scope. Args: caught_exc(Exception): The caught exception object append_msg(str): The message to append to the caught exception prepend(bool): If True prepend the message to args instead of appending Returns: None Side Effects: Re-raises the exception with the preserved data / trace but modified message """ if not caught_exc.args: # If no args, create our own tuple arg_list = [append_msg] else: # Take the last arg # If it is a string # append your message. # Otherwise append it to the # arg list(Not as pretty) arg_list = list(caught_exc.args[:-1]) last_arg = caught_exc.args[-1] if isinstance(last_arg, str): if prepend: arg_list.append(append_msg + last_arg) else: arg_list.append(last_arg + append_msg) else: arg_list += [last_arg, append_msg] caught_exc.args = tuple(arg_list) raise def remove_none(obj): if isinstance(obj, (list, tuple, set)): lst = type(obj)(remove_none(x) for x in obj if x) try: return [dict(t) for t in {tuple(sorted(d.items())) for d in lst}] except (AttributeError, TypeError): return lst elif isinstance(obj, dict): return type(obj)((remove_none(k), remove_none(v)) for k, v in obj.items() if k is not None and v is not None) else: return obj def delete_items_from_dict(d: dict | list, to_delete): """Recursively deletes items from a dict, if the item's value(s) is in ``to_delete``. """ if not isinstance(to_delete, list): to_delete = [to_delete] if isinstance(d, dict): for single_to_delete in set(to_delete): if single_to_delete in d.values(): for k, v in d.copy().items(): if v == single_to_delete: del d[k] for v in d.values(): delete_items_from_dict(v, to_delete) elif isinstance(d, list): for i in d: delete_items_from_dict(i, to_delete) return remove_none(d) def is_valid_metadata_key(name: str) -> bool: # According to the documentation a metadata key # has to be a valid XML tag name. # # The actual allowed tag names (at least as tested with the metadata API), # are way more restrictive and only allow ".-A-Za-z_", possibly followed # by an index in square brackets e. g. [0]. # On the other hand the Archive allows tags starting with the string "xml". return bool(re.fullmatch(r'[A-Za-z][.\-0-9A-Za-z_]+(?:\[[0-9]+\])?', name)) def merge_dictionaries( dict0: dict, dict1: dict, keys_to_drop: Iterable | None = None, ) -> dict: """Merge two dictionaries. Items in `dict0` can optionally be dropped before the merge. If equal keys exist in both dictionaries, entries in`dict0` are overwritten. :param dict0: A base dictionary with the bulk of the items. :param dict1: Additional items which overwrite the items in `dict0`. :param keys_to_drop: An iterable of keys to drop from `dict0` before the merge. :returns: A merged dictionary. """ new_dict = dict0.copy() if keys_to_drop is not None: for key in keys_to_drop: new_dict.pop(key, None) # Items from `dict1` take precedence over items from `dict0`. new_dict.update(dict1) return new_dict def parse_dict_cookies(value: str) -> dict[str, str | None]: result: dict[str, str | None] = {} for item in value.split(';'): item = item.strip() if not item: continue if '=' not in item: result[item] = None continue name, value = item.split('=', 1) result[name] = value if 'domain' not in result: result['domain'] = '.archive.org' if 'path' not in result: result['path'] = '/' return result
14,322
Python
.py
375
29.994667
97
0.606605
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,412
__init__.py
jjjake_internetarchive/internetarchive/__init__.py
# # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2019 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Internetarchive Library ~~~~~~~~~~~~~~~~~~~~~~~ Internetarchive is a python interface to archive.org. Usage:: >>> from internetarchive import get_item >>> item = get_item('govlawgacode20071') >>> item.exists True :copyright: (C) 2012-2019 by Internet Archive. :license: AGPL 3, see LICENSE for more details. """ __title__ = 'internetarchive' __author__ = 'Jacob M. Johnson' __license__ = 'AGPL 3' __copyright__ = 'Copyright (C) 2012-2019 Internet Archive' from .__version__ import __version__ # isort:skip from internetarchive.api import ( configure, delete, download, get_files, get_item, get_session, get_tasks, get_user_info, get_username, modify_metadata, search_items, upload, ) from internetarchive.catalog import Catalog from internetarchive.files import File from internetarchive.item import Item from internetarchive.search import Search from internetarchive.session import ArchiveSession __all__ = [ '__version__', # Classes. 'ArchiveSession', 'Item', 'File', 'Search', 'Catalog', # API. 'get_item', 'get_files', 'modify_metadata', 'upload', 'download', 'delete', 'get_tasks', 'search_items', 'get_session', 'configure', 'get_username', ] # Set default logging handler to avoid "No handler found" warnings. import logging log = logging.getLogger(__name__) log.addHandler(logging.NullHandler())
2,237
Python
.py
78
25.717949
74
0.71575
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,413
catalog.py
jjjake_internetarchive/internetarchive/catalog.py
# # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2019 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ internetarchive.catalog ~~~~~~~~~~~~~~~~~~~~~~~ This module contains objects for interacting with the Archive.org catalog. :copyright: (C) 2012-2019 by Internet Archive. :license: AGPL 3, see LICENSE for more details. """ from __future__ import annotations from datetime import datetime from logging import getLogger from typing import Iterable, Mapping, MutableMapping from requests import Response from requests.exceptions import HTTPError from internetarchive import auth from internetarchive import session as ia_session from internetarchive.utils import json log = getLogger(__name__) def sort_by_date(task_dict: CatalogTask) -> datetime: if task_dict.category == 'summary': # type: ignore return datetime.now() try: return datetime.strptime(task_dict['submittime'], '%Y-%m-%d %H:%M:%S.%f') except Exception: return datetime.strptime(task_dict['submittime'], '%Y-%m-%d %H:%M:%S') class Catalog: """This class represents the Archive.org catalog. You can use this class to access and submit tasks from the catalog. This is a low-level interface, and in most cases the functions in :mod:`internetarchive.api` and methods in :class:`ArchiveSession <ArchiveSession>` should be used. It uses the archive.org `Tasks API <https://archive.org/services/docs/api/tasks.html>`_ Usage:: >>> from internetarchive import get_session, Catalog >>> s = get_session() >>> c = Catalog(s) >>> tasks = c.get_tasks('nasa') >>> tasks[-1].task_id 31643502 """ def __init__( self, archive_session: ia_session.ArchiveSession, request_kwargs: Mapping | None = None, ): """ Initialize :class:`Catalog <Catalog>` object. :param archive_session: An :class:`ArchiveSession <ArchiveSession>` object. :param request_kwargs: Keyword arguments to be used in :meth:`requests.sessions.Session.get` and :meth:`requests.sessions.Session.post` requests. """ self.session = archive_session self.auth = auth.S3Auth(self.session.access_key, self.session.secret_key) self.request_kwargs = request_kwargs or {} self.url = f'{self.session.protocol}//{self.session.host}/services/tasks.php' def get_summary(self, identifier: str = "", params: dict | None = None) -> dict: """Get the total counts of catalog tasks meeting all criteria, organized by run status (queued, running, error, and paused). :param identifier: Item identifier. :param params: Query parameters, refer to `Tasks API <https://archive.org/services/docs/api/tasks.html>`_ for available parameters. :returns: the total counts of catalog tasks meeting all criteria """ params = params or {} if identifier: params['identifier'] = identifier params.update({'summary': 1, 'history': 0, 'catalog': 0}) r = self.make_tasks_request(params) j = r.json() if j.get('success') is True: return j['value']['summary'] else: return j def make_tasks_request(self, params: Mapping | None) -> Response: """Make a GET request to the `Tasks API <https://archive.org/services/docs/api/tasks.html>`_ :param params: Query parameters, refer to `Tasks API <https://archive.org/services/docs/api/tasks.html>`_ for available parameters. :returns: :class:`requests.Response` """ r = self.session.get(self.url, params=params, auth=self.auth, **self.request_kwargs) try: r.raise_for_status() except HTTPError as exc: j = r.json() error = j['error'] raise HTTPError(error, response=r) return r def iter_tasks(self, params: MutableMapping | None = None) -> Iterable[CatalogTask]: """A generator that can make arbitrary requests to the Tasks API. It handles paging (via cursor) automatically. :param params: Query parameters, refer to `Tasks API <https://archive.org/services/docs/api/tasks.html>`_ for available parameters. :returns: collections.Iterable[CatalogTask] """ params = params or {} while True: r = self.make_tasks_request(params) j = r.json() for row in j.get('value', {}).get('catalog', []): yield CatalogTask(row, self) for row in j.get('value', {}).get('history', []): yield CatalogTask(row, self) if not j.get('value', {}).get('cursor'): break params['cursor'] = j['value']['cursor'] def get_rate_limit(self, cmd: str = 'derive.php'): params = {'rate_limits': 1, 'cmd': cmd} r = self.make_tasks_request(params) line = '' tasks = [] for c in r.iter_content(): c = c.decode('utf-8') if c == '\n': j = json.loads(line) task = CatalogTask(j, self) tasks.append(task) line = '' line += c j = json.loads(line) return j def get_tasks(self, identifier: str = "", params: dict | None = None) -> list[CatalogTask]: """Get a list of all tasks meeting all criteria. The list is ordered by submission time. :param identifier: The item identifier, if provided will return tasks for only this item filtered by other criteria provided in params. :param params: Query parameters, refer to `Tasks API <https://archive.org/services/docs/api/tasks.html>`_ for available parameters. :returns: A list of all tasks meeting all criteria. """ params = params or {} if identifier: params.update({'identifier': identifier}) params.update({'limit': 0}) if not params.get('summary'): params['summary'] = 0 r = self.make_tasks_request(params) line = '' tasks = [] for c in r.iter_content(): c = c.decode('utf-8') if c == '\n': j = json.loads(line) task = CatalogTask(j, self) tasks.append(task) line = '' line += c if line.strip(): j = json.loads(line) task = CatalogTask(j, self) tasks.append(task) all_tasks = sorted(tasks, key=sort_by_date, reverse=True) return all_tasks def submit_task(self, identifier: str, cmd: str, comment: str | None = None, priority: int = 0, data: dict | None = None, headers: dict | None = None) -> Response: """Submit an archive.org task. :param identifier: Item identifier. :param cmd: Task command to submit, see `supported task commands <https://archive.org/services/docs/api/tasks.html#supported-tasks>`_. :param comment: A reasonable explanation for why the task is being submitted. :param priority: Task priority from 10 to -10 (default: 0). :param data: Extra POST data to submit with the request. Refer to `Tasks API Request Entity <https://archive.org/services/docs/api/tasks.html#request-entity>`_. :param headers: Add additional headers to request. :returns: :class:`requests.Response` """ data = data or {} data.update({'cmd': cmd, 'identifier': identifier}) if comment: if 'args' in data: data['args']['comment'] = comment else: data['args'] = {'comment': comment} if priority: data['priority'] = priority r = self.session.post(self.url, json=data, auth=self.auth, headers=headers, **self.request_kwargs) return r class CatalogTask: """This class represents an Archive.org catalog task. It is primarily used by :class:`Catalog`, and should not be used directly. """ def __init__(self, task_dict: Mapping, catalog_obj: Catalog): self.session = catalog_obj.session self.request_kwargs = catalog_obj.request_kwargs self.color = None self.task_dict = task_dict for key, value in task_dict.items(): setattr(self, key, value) # Confuses mypy ;-) def __repr__(self): color = self.task_dict.get('color', 'done') return ('CatalogTask(identifier={identifier},' ' task_id={task_id!r}, server={server!r},' ' cmd={cmd!r},' ' submitter={submitter!r},' ' color={task_color!r})'.format(task_color=color, **self.task_dict)) def __getitem__(self, key: str): """Dict-like access provided as backward compatibility.""" return self.task_dict[key] def json(self): return json.dumps(self.task_dict) def task_log(self) -> str: """Get task log. :returns: The task log as a string. """ task_id = self.task_id # type: ignore if task_id is None: raise ValueError('task_id is None') return self.get_task_log(task_id, self.session, self.request_kwargs) @staticmethod def get_task_log( task_id: int | str | None, session: ia_session.ArchiveSession, request_kwargs: Mapping | None = None ) -> str: """Static method for getting a task log, given a task_id. This method exists so a task log can be retrieved without retrieving the items task history first. :param task_id: The task id for the task log you'd like to fetch. :param archive_session: :class:`ArchiveSession <ArchiveSession>` :param request_kwargs: Keyword arguments that :py:class:`requests.Request` takes. :returns: The task log as a string. """ request_kwargs = request_kwargs or {} _auth = auth.S3Auth(session.access_key, session.secret_key) if session.host == 'archive.org': host = 'catalogd.archive.org' else: host = session.host url = f'{session.protocol}//{host}/services/tasks.php' params = {'task_log': task_id} r = session.get(url, params=params, auth=_auth, **request_kwargs) r.raise_for_status() return r.content.decode('utf-8', errors='surrogateescape')
11,922
Python
.py
275
32.814545
95
0.583901
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,414
exceptions.py
jjjake_internetarchive/internetarchive/exceptions.py
# # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2019 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ internetarchive.exceptions ~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (C) 2012-2019 by Internet Archive. :license: AGPL 3, see LICENSE for more details. """ class AuthenticationError(Exception): """Authentication Failed""" class ItemLocateError(Exception): def __init__(self, *args, **kwargs): default_message = "Item cannot be located because it is dark or does not exist." if args or kwargs: super().__init__(*args, **kwargs) else: super().__init__(default_message) class InvalidChecksumError(Exception): def __init__(self, *args, **kwargs): default_message = "File corrupt, checksums do not match." if args or kwargs: super().__init__(*args, **kwargs) else: super().__init__(default_message)
1,586
Python
.py
39
36.692308
88
0.697856
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,415
files.py
jjjake_internetarchive/internetarchive/files.py
# # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2021 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ internetarchive.files ~~~~~~~~~~~~~~~~~~~~~ :copyright: (C) 2012-2019 by Internet Archive. :license: AGPL 3, see LICENSE for more details. """ import logging import os import socket import sys from contextlib import nullcontext, suppress from email.utils import parsedate_to_datetime from time import sleep from urllib.parse import quote from requests.exceptions import ( ConnectionError, ConnectTimeout, HTTPError, ReadTimeout, RetryError, ) from tqdm import tqdm from internetarchive import auth, exceptions, iarequest, utils log = logging.getLogger(__name__) class BaseFile: def __init__(self, item_metadata, name, file_metadata=None): if file_metadata is None: file_metadata = {} name = name.strip('/') if not file_metadata: for f in item_metadata.get('files', []): if f.get('name') == name: file_metadata = f break self.identifier = item_metadata.get('metadata', {}).get('identifier') self.name = name self.size = None self.source = None self.format = None self.md5 = None self.sha1 = None self.mtime = None self.crc32 = None self.exists = bool(file_metadata) for key in file_metadata: setattr(self, key, file_metadata[key]) # An additional, more orderly way to access file metadata, # which avoids filtering the attributes. self.metadata = file_metadata self.mtime = float(self.mtime) if self.mtime else 0 self.size = int(self.size) if self.size else 0 class File(BaseFile): """This class represents a file in an archive.org item. You can use this class to access the file metadata:: >>> import internetarchive >>> item = internetarchive.Item('stairs') >>> file = internetarchive.File(item, 'stairs.avi') >>> print(f.format, f.size) ('Cinepack', '3786730') Or to download a file:: >>> file.download() >>> file.download('fabulous_movie_of_stairs.avi') This class also uses IA's S3-like interface to delete a file from an item. You need to supply your IAS3 credentials in environment variables in order to delete:: >>> file.delete(access_key='Y6oUrAcCEs4sK8ey', ... secret_key='youRSECRETKEYzZzZ') You can retrieve S3 keys here: `https://archive.org/account/s3.php <https://archive.org/account/s3.php>`__ """ def __init__(self, item, name, file_metadata=None): """ :type item: Item :param item: The item that the file is part of. :type name: str :param name: The filename of the file. :type file_metadata: dict :param file_metadata: (optional) a dict of metadata for the given file. """ super().__init__(item.item_metadata, name, file_metadata) self.item = item url_parts = { 'protocol': item.session.protocol, 'id': self.identifier, 'name': quote(name.encode('utf-8')), 'host': item.session.host, } self.url = '{protocol}//{host}/download/{id}/{name}'.format(**url_parts) if self.item.session.access_key and self.item.session.secret_key: self.auth = auth.S3Auth(self.item.session.access_key, self.item.session.secret_key) else: self.auth = None def __repr__(self): return (f'File(identifier={self.identifier!r}, ' f'filename={self.name!r}, ' f'size={self.size!r}, ' f'format={self.format!r})') def download( # noqa: max-complexity=38 self, file_path=None, verbose=None, ignore_existing=None, checksum=None, checksum_archive=None, destdir=None, retries=None, ignore_errors=None, fileobj=None, return_responses=None, no_change_timestamp=None, params=None, chunk_size=None, stdout=None, ors=None, timeout=None, ): """Download the file into the current working directory. :type file_path: str :param file_path: Download file to the given file_path. :type verbose: bool :param verbose: (optional) Turn on verbose output. :type ignore_existing: bool :param ignore_existing: Overwrite local files if they already exist. :type checksum: bool :param checksum: (optional) Skip downloading file based on checksum. :type checksum_archive: bool :param checksum_archive: (optional) Skip downloading file based on checksum, and skip checksum validation if it already succeeded (will create and use _checksum_archive.txt). :type destdir: str :param destdir: (optional) The directory to download files to. :type retries: int :param retries: (optional) The number of times to retry on failed requests. :type ignore_errors: bool :param ignore_errors: (optional) Don't fail if a single file fails to download, continue to download other files. :type fileobj: file-like object :param fileobj: (optional) Write data to the given file-like object (e.g. sys.stdout). :type return_responses: bool :param return_responses: (optional) Rather than downloading files to disk, return a list of response objects. :type no_change_timestamp: bool :param no_change_timestamp: (optional) If True, leave the time stamp as the current time instead of changing it to that given in the original archive. :type stdout: bool :param stdout: (optional) Print contents of file to stdout instead of downloading to file. :type ors: bool :param ors: (optional) Append a newline or $ORS to the end of file. This is mainly intended to be used internally with `stdout`. :type params: dict :param params: (optional) URL parameters to send with download request (e.g. `cnt=0`). :rtype: bool :returns: True if file was successfully downloaded. """ verbose = False if verbose is None else verbose ignore_existing = False if ignore_existing is None else ignore_existing checksum = False if checksum is None else checksum checksum_archive = False if checksum_archive is None else checksum_archive retries = retries or 2 ignore_errors = ignore_errors or False return_responses = return_responses or False no_change_timestamp = no_change_timestamp or False params = params or None timeout = 12 if not timeout else timeout headers = {} retries_sleep = 3 # TODO: exponential sleep retrying = False # for retry loop self.item.session.mount_http_adapter(max_retries=retries) file_path = file_path or self.name if destdir: if return_responses is not True: try: os.mkdir(destdir) except FileExistsError: pass if os.path.isfile(destdir): raise OSError(f'{destdir} is not a directory!') file_path = os.path.join(destdir, file_path) parent_dir = os.path.dirname(file_path) # Check if we should skip... if not return_responses and os.path.exists(file_path.encode('utf-8')): if checksum_archive: checksum_archive_filename = '_checksum_archive.txt' if not os.path.exists(checksum_archive_filename): with open(checksum_archive_filename, 'w', encoding='utf-8') as f: pass with open(checksum_archive_filename, encoding='utf-8') as f: checksum_archive_data = f.read().splitlines() if file_path in checksum_archive_data: msg = ( f'skipping {file_path}, ' f'file already exists based on checksum_archive.' ) log.info(msg) if verbose: print(f' {msg}', file=sys.stderr) return if ignore_existing: msg = f'skipping {file_path}, file already exists.' log.info(msg) if verbose: print(f' {msg}', file=sys.stderr) return elif checksum or checksum_archive: with open(file_path, 'rb') as fp: md5_sum = utils.get_md5(fp) if md5_sum == self.md5: msg = f'skipping {file_path}, file already exists based on checksum.' log.info(msg) if verbose: print(f' {msg}', file=sys.stderr) if checksum_archive: # add file to checksum_archive to skip it next time with open(checksum_archive_filename, 'a', encoding='utf-8') as f: f.write(f'{file_path}\n') return # Retry loop while True: try: if parent_dir != '' and return_responses is not True: os.makedirs(parent_dir, exist_ok=True) if not return_responses \ and not ignore_existing \ and self.name != f'{self.identifier}_files.xml' \ and os.path.exists(file_path.encode('utf-8')): st = os.stat(file_path.encode('utf-8')) if st.st_size != self.size and not (checksum or checksum_archive): headers = {"Range": f"bytes={st.st_size}-"} response = self.item.session.get( self.url, stream=True, timeout=timeout, auth=self.auth, params=params, headers=headers, ) # Get timestamp from Last-Modified header last_mod_header = response.headers.get('Last-Modified') if last_mod_header: dt = parsedate_to_datetime(last_mod_header) last_mod_mtime = dt.timestamp() else: last_mod_mtime = self.mtime response.raise_for_status() # Check if we should skip based on last modified time... if not fileobj and not return_responses and os.path.exists(file_path.encode('utf-8')): st = os.stat(file_path.encode('utf-8')) if st.st_mtime == last_mod_mtime: if self.name == f'{self.identifier}_files.xml' or (st.st_size == self.size): msg = (f'skipping {file_path}, file already exists based on ' 'length and date.') log.info(msg) if verbose: print(f' {msg}', file=sys.stderr) return elif return_responses: return response if verbose: total = int(response.headers.get('content-length', 0)) or None progress_bar = tqdm(desc=f' downloading {self.name}', total=total, unit='iB', unit_scale=True, unit_divisor=1024) else: progress_bar = nullcontext() if not chunk_size: chunk_size = 1048576 if stdout: fileobj = os.fdopen(sys.stdout.fileno(), 'wb', closefd=False) if not fileobj or retrying: if 'Range' in headers: fileobj = open(file_path.encode('utf-8'), 'rb+') else: fileobj = open(file_path.encode('utf-8'), 'wb') with fileobj, progress_bar as bar: if 'Range' in headers: fileobj.seek(st.st_size) for chunk in response.iter_content(chunk_size=chunk_size): if chunk: size = fileobj.write(chunk) if bar is not None: bar.update(size) if ors: fileobj.write(os.environ.get("ORS", "\n").encode("utf-8")) if 'Range' in headers: with open(file_path, 'rb') as fh: local_checksum = utils.get_md5(fh) try: assert local_checksum == self.md5 except AssertionError: msg = (f"\"{file_path}\" corrupt, " "checksums do not match. " "Remote file may have been modified, " "retry download.") os.remove(file_path.encode('utf-8')) raise exceptions.InvalidChecksumError(msg) break except (RetryError, HTTPError, ConnectTimeout, OSError, ReadTimeout, exceptions.InvalidChecksumError) as exc: if retries > 0: retrying = True retries -= 1 msg = ('download failed, sleeping for ' f'{retries_sleep} seconds and retrying. ' f'{retries} retries left.') log.warning(msg) sleep(retries_sleep) continue msg = f'error downloading file {file_path}, exception raised: {exc}' log.error(msg) try: os.remove(file_path) except OSError: pass if verbose: print(f' {msg}', file=sys.stderr) if ignore_errors: return False else: raise exc # Set mtime with timestamp from Last-Modified header if not no_change_timestamp: # If we want to set the timestamp to that of the original archive... with suppress(OSError): # Probably file-like object, e.g. sys.stdout. os.utime(file_path.encode('utf-8'), (0,last_mod_mtime)) msg = f'downloaded {self.identifier}/{self.name} to {file_path}' log.info(msg) return True def delete(self, cascade_delete=None, access_key=None, secret_key=None, verbose=None, debug=None, retries=None, headers=None): """Delete a file from the Archive. Note: Some files -- such as <itemname>_meta.xml -- cannot be deleted. :type cascade_delete: bool :param cascade_delete: (optional) Delete all files associated with the specified file, including upstream derivatives and the original. :type access_key: str :param access_key: (optional) IA-S3 access_key to use when making the given request. :type secret_key: str :param secret_key: (optional) IA-S3 secret_key to use when making the given request. :type verbose: bool :param verbose: (optional) Print actions to stdout. :type debug: bool :param debug: (optional) Set to True to print headers to stdout and exit exit without sending the delete request. """ cascade_delete = '0' if not cascade_delete else '1' access_key = self.item.session.access_key if not access_key else access_key secret_key = self.item.session.secret_key if not secret_key else secret_key debug = debug or False verbose = verbose or False max_retries = retries or 2 headers = headers or {} if 'x-archive-cascade-delete' not in headers: headers['x-archive-cascade-delete'] = cascade_delete url = f'{self.item.session.protocol}//s3.us.archive.org/{self.identifier}/{quote(self.name)}' self.item.session.mount_http_adapter(max_retries=max_retries, status_forcelist=[503], host='s3.us.archive.org') request = iarequest.S3Request( method='DELETE', url=url, headers=headers, access_key=access_key, secret_key=secret_key ) if debug: return request else: if verbose: msg = f' deleting: {self.name}' if cascade_delete: msg += ' and all derivative files.' print(msg, file=sys.stderr) prepared_request = self.item.session.prepare_request(request) try: resp = self.item.session.send(prepared_request) resp.raise_for_status() except (RetryError, HTTPError, ConnectTimeout, OSError, ReadTimeout) as exc: error_msg = f'Error deleting {url}, {exc}' log.error(error_msg) raise else: return resp finally: # The retry adapter is mounted to the session object. # Make sure to remove it after delete, so it isn't # mounted if and when the session object is used for an # upload. This is important because we use custom retry # handling for IA-S3 uploads. url_prefix = f'{self.item.session.protocol}//s3.us.archive.org' del self.item.session.adapters[url_prefix] class OnTheFlyFile(File): def __init__(self, item, name): """ :type item: Item :param item: The item that the file is part of. :type name: str :param name: The filename of the file. """ super().__init__(item.item_metadata, name)
19,599
Python
.py
429
31.37296
102
0.541937
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,416
session.py
jjjake_internetarchive/internetarchive/session.py
# # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2021 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ internetarchive.session ~~~~~~~~~~~~~~~~~~~~~~~ This module provides an ArchiveSession object to manage and persist settings across the internetarchive package. :copyright: (C) 2012-2021 by Internet Archive. :license: AGPL 3, see LICENSE for more details. """ from __future__ import annotations import locale import logging import os import platform import sys import warnings from typing import Iterable, Mapping, MutableMapping from urllib.parse import unquote, urlparse import requests.sessions from requests import Response from requests.adapters import HTTPAdapter from requests.cookies import create_cookie from requests.utils import default_headers from urllib3 import Retry from internetarchive import __version__, auth, catalog from internetarchive.config import get_config from internetarchive.item import Collection, Item from internetarchive.search import Search from internetarchive.utils import parse_dict_cookies, reraise_modify logger = logging.getLogger(__name__) class ArchiveSession(requests.sessions.Session): """The :class:`ArchiveSession <internetarchive.ArchiveSession>` object collects together useful functionality from `internetarchive` as well as important data such as configuration information and credentials. It is subclassed from :class:`requests.Session <requests.Session>`. Usage:: >>> from internetarchive import ArchiveSession >>> s = ArchiveSession() >>> item = s.get_item('nasa') Collection(identifier='nasa', exists=True) """ ITEM_MEDIATYPE_TABLE = { 'collection': Collection, } def __init__(self, config: Mapping | None = None, config_file: str = "", debug: bool = False, http_adapter_kwargs: MutableMapping | None = None): """Initialize :class:`ArchiveSession <ArchiveSession>` object with config. :param config: A config dict used for initializing the :class:`ArchiveSession <ArchiveSession>` object. :param config_file: Path to config file used for initializing the :class:`ArchiveSession <ArchiveSession>` object. :param http_adapter_kwargs: Keyword arguments used to initialize the :class:`requests.adapters.HTTPAdapter <HTTPAdapter>` object. :returns: :class:`ArchiveSession` object. """ super().__init__() http_adapter_kwargs = http_adapter_kwargs or {} debug = bool(debug) self.config = get_config(config, config_file) self.config_file = config_file for ck, cv in self.config.get('cookies', {}).items(): raw_cookie = f'{ck}={cv}' cookie_dict = parse_dict_cookies(raw_cookie) if not cookie_dict.get(ck): continue cookie = create_cookie(ck, cookie_dict[ck], domain=cookie_dict.get('domain', '.archive.org'), path=cookie_dict.get('path', '/')) self.cookies.set_cookie(cookie) self.secure: bool = self.config.get('general', {}).get('secure', True) self.host: str = self.config.get('general', {}).get('host', 'archive.org') if 'archive.org' not in self.host: self.host += '.archive.org' self.protocol = 'https:' if self.secure else 'http:' user_email = self.config.get('cookies', {}).get('logged-in-user') if user_email: user_email = user_email.split(';')[0] user_email = unquote(user_email) self.user_email: str = user_email self.access_key: str = self.config.get('s3', {}).get('access') self.secret_key: str = self.config.get('s3', {}).get('secret') self.http_adapter_kwargs: MutableMapping = http_adapter_kwargs or {} self.headers = default_headers() # type: ignore[assignment] self.headers.update({'User-Agent': self._get_user_agent_string()}) self.headers.update({'Connection': 'close'}) self.mount_http_adapter() logging_config = self.config.get('logging', {}) if logging_config.get('level'): self.set_file_logger(logging_config.get('level', 'NOTSET'), logging_config.get('file', 'internetarchive.log')) if debug or (logger.level <= 10): self.set_file_logger(logging_config.get('level', 'NOTSET'), logging_config.get('file', 'internetarchive.log'), 'urllib3') def _get_user_agent_string(self) -> str: """Generate a User-Agent string to be sent with every request.""" uname = platform.uname() try: lang = locale.getlocale()[0][:2] # type: ignore except Exception: lang = '' py_version = '{}.{}.{}'.format(*sys.version_info) return (f'internetarchive/{__version__} ' f'({uname[0]} {uname[-1]}; N; {lang}; {self.access_key}) ' f'Python/{py_version}') def rebuild_auth(self, prepared_request, response): """Never rebuild auth for archive.org URLs. """ u = urlparse(prepared_request.url) if u.netloc.endswith('archive.org'): return super().rebuild_auth(prepared_request, response) def mount_http_adapter(self, protocol: str | None = None, max_retries: int | None = None, status_forcelist: list | None = None, host: str | None = None) -> None: """Mount an HTTP adapter to the :class:`ArchiveSession <ArchiveSession>` object. :param protocol: HTTP protocol to mount your adapter to (e.g. 'https://'). :param max_retries: The number of times to retry a failed request. This can also be an `urllib3.Retry` object. :param status_forcelist: A list of status codes (as int's) to retry on. :param host: The host to mount your adapter to. """ protocol = protocol or self.protocol host = host or 'archive.org' if max_retries is None: max_retries = self.http_adapter_kwargs.get('max_retries', 3) status_forcelist = status_forcelist or [500, 501, 502, 503, 504] if max_retries and isinstance(max_retries, (int, float)): self.http_adapter_kwargs['max_retries'] = Retry(total=max_retries, connect=max_retries, read=max_retries, redirect=False, allowed_methods=Retry.DEFAULT_ALLOWED_METHODS, status_forcelist=status_forcelist, backoff_factor=1) else: self.http_adapter_kwargs['max_retries'] = max_retries max_retries_adapter = HTTPAdapter(**self.http_adapter_kwargs) # Don't mount on s3.us.archive.org, only archive.org! # IA-S3 requires a more complicated retry workflow. self.mount(f'{protocol}//{host}', max_retries_adapter) def set_file_logger( self, log_level: str, path: str, logger_name: str = 'internetarchive' ) -> None: """Convenience function to quickly configure any level of logging to a file. :param log_level: A log level as specified in the `logging` module. :param path: Path to the log file. The file will be created if it doesn't already exist. :param logger_name: The name of the logger. """ _log_level = { 'CRITICAL': 50, 'ERROR': 40, 'WARNING': 30, 'INFO': 20, 'DEBUG': 10, 'NOTSET': 0, } log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' _log = logging.getLogger(logger_name) _log.setLevel(logging.DEBUG) fh = logging.FileHandler(path, encoding='utf-8') fh.setLevel(_log_level[log_level]) formatter = logging.Formatter(log_format) fh.setFormatter(formatter) _log.addHandler(fh) def get_item(self, identifier: str, item_metadata: Mapping | None = None, request_kwargs: MutableMapping | None = None): """A method for creating :class:`internetarchive.Item <Item>` and :class:`internetarchive.Collection <Collection>` objects. :param identifier: A globally unique Archive.org identifier. :param item_metadata: A metadata dict used to initialize the Item or Collection object. Metadata will automatically be retrieved from Archive.org if nothing is provided. :param request_kwargs: Keyword arguments to be used in :meth:`requests.sessions.Session.get` request. """ request_kwargs = request_kwargs or {} if not item_metadata: logger.debug(f'no metadata provided for "{identifier}", retrieving now.') item_metadata = self.get_metadata(identifier, request_kwargs) or {} mediatype = item_metadata.get('metadata', {}).get('mediatype') try: item_class = self.ITEM_MEDIATYPE_TABLE.get(mediatype, Item) except TypeError: item_class = Item return item_class(self, identifier, item_metadata) def get_metadata(self, identifier: str, request_kwargs: MutableMapping | None = None): """Get an item's metadata from the `Metadata API <http://blog.archive.org/2013/07/04/metadata-api/>`__ :param identifier: Globally unique Archive.org identifier. :returns: Metadat API response. """ request_kwargs = request_kwargs or {} url = f'{self.protocol}//{self.host}/metadata/{identifier}' if 'timeout' not in request_kwargs: request_kwargs['timeout'] = 12 try: if self.access_key and self.secret_key: s3_auth = auth.S3Auth(self.access_key, self.secret_key) else: s3_auth = None resp = self.get(url, auth=s3_auth, **request_kwargs) resp.raise_for_status() except Exception as exc: error_msg = f'Error retrieving metadata from {url}, {exc}' logger.error(error_msg) raise type(exc)(error_msg) return resp.json() def search_items(self, query: str, fields: Iterable[str] | None = None, sorts: Iterable[str] | None = None, params: Mapping | None = None, full_text_search: bool = False, dsl_fts: bool = False, request_kwargs: Mapping | None = None, max_retries: int | Retry | None = None) -> Search: """Search for items on Archive.org. :param query: The Archive.org search query to yield results for. Refer to https://archive.org/advancedsearch.php#raw for help formatting your query. :param fields: The metadata fields to return in the search results. :param params: The URL parameters to send with each request sent to the Archive.org Advancedsearch Api. :param full_text_search: Beta support for querying the archive.org Full Text Search API [default: False]. :param dsl_fts: Beta support for querying the archive.org Full Text Search API in dsl (i.e. do not prepend ``!L `` to the ``full_text_search`` query [default: False]. :returns: A :class:`Search` object, yielding search results. """ request_kwargs = request_kwargs or {} return Search(self, query, fields=fields, sorts=sorts, params=params, full_text_search=full_text_search, dsl_fts=dsl_fts, request_kwargs=request_kwargs, max_retries=max_retries) def s3_is_overloaded(self, identifier=None, access_key=None, request_kwargs=None): request_kwargs = request_kwargs or {} if 'timeout' not in request_kwargs: request_kwargs['timeout'] = 12 u = f'{self.protocol}//s3.us.archive.org' p = { 'check_limit': 1, 'accesskey': access_key, 'bucket': identifier, } try: r = self.get(u, params=p, **request_kwargs) except Exception: return True try: j = r.json() except ValueError: return True return j.get('over_limit') != 0 def get_tasks_api_rate_limit(self, cmd: str = 'derive.php', request_kwargs: dict | None = None): return catalog.Catalog(self, request_kwargs).get_rate_limit(cmd=cmd) def submit_task(self, identifier: str, cmd: str, comment: str = '', priority: int = 0, data: dict | None = None, headers: dict | None = None, reduced_priority: bool = False, request_kwargs: Mapping | None = None) -> requests.Response: """Submit an archive.org task. :param identifier: Item identifier. :param cmd: Task command to submit, see `supported task commands <https://archive.org/services/docs/api/tasks.html#supported-tasks>`_. :param comment: A reasonable explanation for why the task is being submitted. :param priority: Task priority from 10 to -10 (default: 0). :param data: Extra POST data to submit with the request. Refer to `Tasks API Request Entity <https://archive.org/services/docs/api/tasks.html#request-entity>`_. :param headers: Add additional headers to request. :param reduced_priority: Submit your derive at a lower priority. This option is helpful to get around rate-limiting. Your task will more likely be accepted, but it might not run for a long time. Note that you still may be subject to rate-limiting. This is different than ``priority`` in that it will allow you to possibly avoid rate-limiting. :param request_kwargs: Keyword arguments to be used in :meth:`requests.sessions.Session.post` request. :returns: :class:`requests.Response` """ headers = headers or {} if reduced_priority: headers.update({'X-Accept-Reduced-Priority': '1'}) return catalog.Catalog(self, request_kwargs).submit_task(identifier, cmd, comment=comment, priority=priority, data=data, headers=headers) def iter_history(self, identifier: str | None, params: dict | None = None, request_kwargs: Mapping | None = None) -> Iterable[catalog.CatalogTask]: """A generator that returns completed tasks. :param identifier: Item identifier. :param params: Query parameters, refer to `Tasks API <https://archive.org/services/docs/api/tasks.html>`_ for available parameters. :param request_kwargs: Keyword arguments to be used in :meth:`requests.sessions.Session.get` request. :returns: An iterable of completed CatalogTasks. """ params = params or {} params.update({'identifier': identifier, 'catalog': 0, 'summary': 0, 'history': 1}) c = catalog.Catalog(self, request_kwargs) yield from c.iter_tasks(params) def iter_catalog(self, identifier: str | None = None, params: dict | None = None, request_kwargs: Mapping | None = None) -> Iterable[catalog.CatalogTask]: """A generator that returns queued or running tasks. :param identifier: Item identifier. :param params: Query parameters, refer to `Tasks API <https://archive.org/services/docs/api/tasks.html>`_ for available parameters. :param request_kwargs: Keyword arguments to be used in :meth:`requests.sessions.Session.get` request. :returns: An iterable of queued or running CatalogTasks. """ params = params or {} params.update({'identifier': identifier, 'catalog': 1, 'summary': 0, 'history': 0}) c = catalog.Catalog(self, request_kwargs) yield from c.iter_tasks(params) def get_tasks_summary(self, identifier: str = "", params: dict | None = None, request_kwargs: Mapping | None = None) -> dict: """Get the total counts of catalog tasks meeting all criteria, organized by run status (queued, running, error, and paused). :param identifier: Item identifier. :param params: Query parameters, refer to `Tasks API <https://archive.org/services/docs/api/tasks.html>`_ for available parameters. :param request_kwargs: Keyword arguments to be used in :meth:`requests.sessions.Session.get` request. :returns: Counts of catalog tasks meeting all criteria. """ return catalog.Catalog(self, request_kwargs).get_summary(identifier=identifier, params=params) def get_tasks(self, identifier: str = "", params: dict | None = None, request_kwargs: Mapping | None = None) -> set[catalog.CatalogTask]: """Get a list of all tasks meeting all criteria. The list is ordered by submission time. :param identifier: The item identifier, if provided will return tasks for only this item filtered by other criteria provided in params. :param params: Query parameters, refer to `Tasks API <https://archive.org/services/docs/api/tasks.html>`_ for available parameters. :param request_kwargs: Keyword arguments to be used in :meth:`requests.sessions.Session.get` request. :returns: A set of all tasks meeting all criteria. """ params = params or {} if 'history' not in params: params['history'] = 1 if 'catalog' not in params: params['catalog'] = 1 return set(catalog.Catalog(self, request_kwargs).get_tasks( identifier=identifier, params=params) ) def get_my_catalog(self, params: dict | None = None, request_kwargs: Mapping | None = None) -> set[catalog.CatalogTask]: """Get all queued or running tasks. :param params: Query parameters, refer to `Tasks API <https://archive.org/services/docs/api/tasks.html>`_ for available parameters. :param request_kwargs: Keyword arguments to be used in :meth:`requests.sessions.Session.get` request. :returns: A set of all queued or running tasks. """ params = params or {} _params = {'submitter': self.user_email, 'catalog': 1, 'history': 0, 'summary': 0} params.update(_params) return self.get_tasks(params=params, request_kwargs=request_kwargs) def get_task_log(self, task_id: str | int, request_kwargs: Mapping | None = None) -> str: """Get a task log. :param task_id: The task id for the task log you'd like to fetch. :param request_kwargs: Keyword arguments that :py:class:`requests.Request` takes. :returns: The task log as a string. """ return catalog.CatalogTask.get_task_log(task_id, self, request_kwargs) def send(self, request, **kwargs) -> Response: # Catch urllib3 warnings for HTTPS related errors. insecure = False with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always') try: r = super().send(request, **kwargs) except Exception as e: try: reraise_modify(e, e.request.url, prepend=False) # type: ignore except Exception: logger.error(e) raise e if self.protocol == 'http:': return r insecure_warnings = ['SNIMissingWarning', 'InsecurePlatformWarning'] if w: for warning in w: if any(x in str(warning) for x in insecure_warnings): insecure = True break if insecure: from requests.exceptions import RequestException msg = ('You are attempting to make an HTTPS request on an insecure platform,' ' please see:\n\n\thttps://archive.org/services/docs/api' '/internetarchive/troubleshooting.html#https-issues\n') raise RequestException(msg) return r
22,967
Python
.py
458
36.786026
102
0.5767
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,417
ia_reviews.py
jjjake_internetarchive/internetarchive/cli/ia_reviews.py
# # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2019 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Submit and modify reviews for archive.org items. For more information on how to use this command, refer to the Reviews API documentation:: https://archive.org/services/docs/api/reviews.html usage: ia reviews <identifier> ia reviews <identifier> --delete [--username=<username> | --screenname=<screenname> | --itemname=<itemname>] ia reviews <identifier> --title=<title> --body=<body> [--stars=<stars>] ia reviews --help options: -h, --help -t, --title=<title> The title of your review. -b, --body=<body> The body of your review. -s, --stars=<stars> The number of stars for your review. -d, --delete Delete your review. [default: False] -u, --username=<username> Delete reviews for a specific user given username (must be used with --delete). -S, --screenname=<screenname> Delete reviews for a specific user given screenname (must be used with --delete). -I, --itemname=<itemname> Delete reviews for a specific user given itemname (must be used with --delete). examples: ia reviews nasa """ import sys from docopt import docopt from requests.exceptions import HTTPError from internetarchive import ArchiveSession def main(argv, session: ArchiveSession) -> None: args = docopt(__doc__, argv=argv) item = session.get_item(args['<identifier>']) if args['--delete']: r = item.delete_review(username=args['--username'], screenname=args['--screenname'], itemname=args['--itemname']) elif not args['--body']: try: r = item.get_review() print(r.text) sys.exit(0) except HTTPError as exc: if exc.response.status_code == 404: # type: ignore sys.exit(0) else: raise exc else: r = item.review(args['--title'], args['--body'], args['--stars']) j = r.json() if j.get('success') or 'no change detected' in j.get('error', '').lower(): task_id = j.get('value', {}).get('task_id') if task_id: print(f'{item.identifier} - success: https://catalogd.archive.org/log/{task_id}', file=sys.stderr) else: print(f'{item.identifier} - warning: no changes detected!', file=sys.stderr) sys.exit(0) else: print(f'{item.identifier} - error: {j.get("error")}', file=sys.stderr) sys.exit(1)
3,428
Python
.py
77
36.753247
93
0.616467
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,418
ia_search.py
jjjake_internetarchive/internetarchive/cli/ia_search.py
# # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2019 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Search items on Archive.org. usage: ia search <query>... [options]... ia search --help options: -h, --help -p, --parameters=<key:value>... Parameters to send with your query. -H, --header=<key:value>... Add custom headers to your search request. -s, --sort=<field order>... Sort search results by specified fields. <order> can be either "asc" for ascending and "desc" for descending. -i, --itemlist Output identifiers only. -f, --field=<field>... Metadata fields to return. -n, --num-found Print the number of results to stdout. -F, --fts Beta support for querying the archive.org full text search API. -D, --dsl-fts Submit --fts query in dsl [default: False]. -t, --timeout=<seconds> Set the timeout in seconds [default: 300]. examples: ia search 'collection:nasa' --parameters rows:1 """ from __future__ import annotations import sys from itertools import chain from docopt import docopt, printable_usage from requests.exceptions import ConnectTimeout, ReadTimeout from schema import And, Or, Schema, SchemaError, Use # type: ignore[import] from internetarchive import ArchiveSession, search_items from internetarchive.cli.argparser import get_args_dict from internetarchive.exceptions import AuthenticationError from internetarchive.utils import json def main(argv, session: ArchiveSession | None = None) -> None: args = docopt(__doc__, argv=argv) # Validate args. s = Schema({ str: Use(bool), '<query>': Use(lambda x: ' '.join(x)), '--parameters': Use(lambda x: get_args_dict(x, query_string=True)), '--header': Or(None, And(Use(get_args_dict), dict), error='--header must be formatted as --header="key:value"'), '--sort': list, '--field': list, '--timeout': Use(lambda x: float(x[0]), error='--timeout must be integer or float.') }) try: args = s.validate(args) except SchemaError as exc: print(f'{exc}\n{printable_usage(__doc__)}', file=sys.stderr) sys.exit(1) # Support comma separated values. fields = list(chain.from_iterable([x.split(',') for x in args['--field']])) sorts = list(chain.from_iterable([x.split(',') for x in args['--sort']])) r_kwargs = { 'headers': args['--header'], 'timeout': args['--timeout'], } search = session.search_items(args['<query>'], # type: ignore fields=fields, sorts=sorts, params=args['--parameters'], full_text_search=args['--fts'], dsl_fts=args['--dsl-fts'], request_kwargs=r_kwargs) try: if args['--num-found']: print(search.num_found) sys.exit(0) for result in search: if args['--itemlist']: if args['--fts'] or args['--dsl-fts']: print('\n'.join(result.get('fields', {}).get('identifier'))) else: print(result.get('identifier', '')) else: j = json.dumps(result) print(j) if result.get('error'): sys.exit(1) except ValueError as e: print(f'error: {e}', file=sys.stderr) except ConnectTimeout as exc: print('error: Request timed out. Increase the --timeout and try again.', file=sys.stderr) sys.exit(1) except ReadTimeout as exc: print('error: The server timed out and failed to return all search results,' ' please try again', file=sys.stderr) sys.exit(1) except AuthenticationError as exc: print(f'error: {exc}', file=sys.stderr) sys.exit(1)
4,859
Python
.py
109
35.477064
84
0.58872
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,419
ia_move.py
jjjake_internetarchive/internetarchive/cli/ia_move.py
# # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2019 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Move and rename files in archive.org items. usage: ia move <src-identifier>/<src-file> <dest-identifier>/<dest-file> [options]... ia move --help options: -h, --help -m, --metadata=<key:value>... Metadata to add to your new item, if you are moving the file to a new item. -H, --header=<key:value>... S3 HTTP headers to send with your request. -n, --no-derive Do not derive uploaded files. --no-backup Turn off archive.org backups. Clobbered files will not be saved to history/files/$key.~N~ [default: True]. """ import sys from docopt import docopt, printable_usage from schema import And, Or, Schema, SchemaError, Use # type: ignore[import] from internetarchive import ArchiveSession from internetarchive.cli import ia_copy from internetarchive.cli.argparser import get_args_dict def main(argv, session: ArchiveSession) -> None: args = docopt(__doc__, argv=argv) src_path = args['<src-identifier>/<src-file>'] dest_path = args['<dest-identifier>/<dest-file>'] # Validate args. s = Schema({ str: Use(bool), '--metadata': list, '--header': Or(None, And(Use(get_args_dict), dict), error='--header must be formatted as --header="key:value"'), '<src-identifier>/<src-file>': And(str, lambda x: '/' in x, error='Source not formatted correctly. See usage example.'), '<dest-identifier>/<dest-file>': And(str, lambda x: '/' in x, error='Destination not formatted correctly. See usage example.'), }) try: args = s.validate(args) except SchemaError as exc: print(f'{exc}\n{printable_usage(__doc__)}', file=sys.stderr) sys.exit(1) # Add keep-old-version by default. if not args['--header'].get('x-archive-keep-old-version') and not args['--no-backup']: args['--header']['x-archive-keep-old-version'] = '1' # First we use ia_copy, prep argv for ia_copy. argv.pop(0) argv = ['copy'] + argv # Call ia_copy. r, src_file = ia_copy.main(argv, session, cmd='move') dr = src_file.delete(headers=args['--header'], cascade_delete=True) if dr.status_code == 204: print(f'success: moved {src_path} to {dest_path}', file=sys.stderr) sys.exit(0) print(f'error: {dr.content}', file=sys.stderr)
3,225
Python
.py
70
40.214286
90
0.652354
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,420
argparser.py
jjjake_internetarchive/internetarchive/cli/argparser.py
# # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2019 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ internetarchive.cli.argparser ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (C) 2012-2019 by Internet Archive. :license: AGPL 3, see LICENSE for more details. """ from __future__ import annotations import sys from collections import defaultdict from typing import Mapping from urllib.parse import parse_qsl def get_args_dict(args: list[str], query_string: bool = False, header: bool = False) -> dict: args = args or [] metadata: dict[str, list | str] = defaultdict(list) for md in args: if query_string: if (':' in md) and ('=' not in md): md = md.replace(':', '=').replace(';', '&') for key, value in parse_qsl(md): assert value metadata[key] = value else: key, value = md.split(':', 1) assert value if value not in metadata[key]: metadata[key].append(value) # type: ignore for key in metadata: # Flatten single item lists. if len(metadata[key]) <= 1: metadata[key] = metadata[key][0] return metadata def get_args_header_dict(args: list[str]) -> dict: h = get_args_dict(args) return {k: v.strip() for k, v in h.items()} def get_args_dict_many_write(metadata: Mapping): changes: dict[str, dict] = defaultdict(dict) for key, value in metadata.items(): target = '/'.join(key.split('/')[:-1]) field = key.split('/')[-1] if not changes[target]: changes[target] = {field: value} else: changes[target][field] = value return changes def convert_str_list_to_unicode(str_list: list[bytes]): encoding = sys.getfilesystemencoding() return [b.decode(encoding) for b in str_list]
2,528
Python
.py
64
34.046875
93
0.654835
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,421
ia_upload.py
jjjake_internetarchive/internetarchive/cli/ia_upload.py
# # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2019 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Upload files to Archive.org. usage: ia upload <identifier> <file>... [options]... ia upload <identifier> - --remote-name=<name> [options]... ia upload <identifier> <file> --remote-name=<name> [options]... ia upload --spreadsheet=<metadata.csv> [options]... ia upload <identifier> --file-metadata=<file_md.jsonl> [options]... ia upload <identifier> --status-check ia upload --help options: -h, --help -q, --quiet Turn off ia's output [default: False]. -d, --debug Print S3 request parameters to stdout and exit without sending request. -r, --remote-name=<name> When uploading data from stdin, this option sets the remote filename. -S, --spreadsheet=<metadata.csv> Bulk uploading. -f, --file-metadata=<file_md.jsonl> Upload files with file-level metadata via a file_md.jsonl file. -m, --metadata=<key:value>... Metadata to add to your item. -H, --header=<key:value>... S3 HTTP headers to send with your request. -c, --checksum Skip based on checksum. [default: False] -v, --verify Verify that data was not corrupted traversing the network. [default: False] -n, --no-derive Do not derive uploaded files. --size-hint=<size> Specify a size-hint for your item. --delete Delete files after verifying checksums [default: False]. -R, --retries=<i> Number of times to retry request if S3 returns a 503 SlowDown error. -s, --sleep=<i> The amount of time to sleep between retries [default: 30]. --status-check Check if S3 is accepting requests to the given item. --no-collection-check Skip collection exists check [default: False]. -o, --open-after-upload Open the details page for an item after upload [default: False]. --no-backup Turn off archive.org backups. Clobbered files will not be saved to history/files/$key.~N~ [default: True]. --keep-directories Keep directories in the supplied file paths for the remote filename. [default: False] --no-scanner Do not set the scanner field in meta.xml. """ import csv import os import sys import webbrowser from copy import deepcopy from locale import getpreferredencoding from pathlib import Path from tempfile import TemporaryFile from docopt import docopt, printable_usage from requests.exceptions import HTTPError from schema import And, Or, Schema, SchemaError, Use # type: ignore[import] from internetarchive.cli.argparser import convert_str_list_to_unicode, get_args_dict from internetarchive.session import ArchiveSession from internetarchive.utils import ( InvalidIdentifierException, JSONDecodeError, get_s3_xml_text, is_valid_metadata_key, json, validate_s3_identifier, ) def _upload_files(item, files, upload_kwargs, prev_identifier=None, archive_session=None): """Helper function for calling :meth:`Item.upload`""" # Check if the list has any element. if not files: raise FileNotFoundError("No valid file was found. Check your paths.") responses = [] if (upload_kwargs['verbose']) and (prev_identifier != item.identifier): print(f'{item.identifier}:', file=sys.stderr) try: response = item.upload(files, **upload_kwargs) responses += response except HTTPError as exc: responses += [exc.response] except InvalidIdentifierException as exc: print(str(exc), file=sys.stderr) sys.exit(1) finally: # Debug mode. if upload_kwargs['debug']: for i, r in enumerate(responses): if i != 0: print('---', file=sys.stderr) headers = '\n'.join( [f' {k}:{v}' for (k, v) in r.headers.items()] ) print(f'Endpoint:\n {r.url}\n', file=sys.stderr) print(f'HTTP Headers:\n{headers}', file=sys.stderr) return responses def main(argv, session): # noqa: C901 args = docopt(__doc__, argv=argv) ERRORS = False # Validate args. s = Schema({ str: Use(bool), '<identifier>': Or(None, And(str, validate_s3_identifier, error=('<identifier> should be between 3 and 80 characters in length, and ' 'can only contain alphanumeric characters, periods ".", ' 'underscores "_", or dashes "-". However, <identifier> cannot begin ' 'with periods, underscores, or dashes.'))), '<file>': And( And(lambda f: all(os.path.exists(x) for x in f if x != '-'), error='<file> should be a readable file or directory.'), And(lambda f: False if f == ['-'] and not args['--remote-name'] else True, error='--remote-name must be provided when uploading from stdin.')), '--remote-name': Or(None, str), '--spreadsheet': Or(None, os.path.isfile, error='--spreadsheet should be a readable file.'), '--file-metadata': Or(None, os.path.isfile, error='--file-metadata should be a readable file.'), '--metadata': Or(None, And(Use(get_args_dict), dict), error='--metadata must be formatted as --metadata="key:value"'), '--header': Or(None, And(Use(get_args_dict), dict), error='--header must be formatted as --header="key:value"'), '--retries': Use(lambda x: int(x[0]) if x else 0), '--sleep': Use(lambda lst: int(lst[0]), error='--sleep value must be an integer.'), '--size-hint': Or(Use(lambda lst: str(lst[0]) if lst else None), int, None, error='--size-hint value must be an integer.'), '--status-check': bool, }) try: args = s.validate(args) except SchemaError as exc: print(f'{exc}\n{printable_usage(__doc__)}', file=sys.stderr) sys.exit(1) # Make sure the collection being uploaded to exists. collection_id = args['--metadata'].get('collection') if collection_id and not args['--no-collection-check'] and not args['--status-check']: if isinstance(collection_id, list): collection_id = collection_id[0] collection = session.get_item(collection_id) if not collection.exists: print('You must upload to a collection that exists. ' f'"{collection_id}" does not exist.\n{printable_usage(__doc__)}', file=sys.stderr) sys.exit(1) # Status check. if args['--status-check']: if session.s3_is_overloaded(): print(f'warning: {args["<identifier>"]} is over limit, and not accepting requests. ' 'Expect 503 SlowDown errors.', file=sys.stderr) sys.exit(1) else: print(f'success: {args["<identifier>"]} is accepting requests.', file=sys.stderr) sys.exit() elif args['<identifier>']: item = session.get_item(args['<identifier>']) # Upload keyword arguments. if args['--size-hint']: args['--header']['x-archive-size-hint'] = args['--size-hint'] # Upload with backups turned on by default. if not args['--header'].get('x-archive-keep-old-version') and not args['--no-backup']: args['--header']['x-archive-keep-old-version'] = '1' queue_derive = True if args['--no-derive'] is False else False verbose = True if args['--quiet'] is False else False set_scanner = False if args['--no-scanner'] is True else True if args['--file-metadata']: try: with open(args['--file-metadata']) as fh: args['<file>'] = json.load(fh) except JSONDecodeError: args['<file>'] = [] with open(args['--file-metadata']) as fh: for line in fh: j = json.loads(line.strip()) args['<file>'].append(j) upload_kwargs = { 'metadata': args['--metadata'], 'headers': args['--header'], 'debug': args['--debug'], 'queue_derive': queue_derive, 'set_scanner': set_scanner, 'verbose': verbose, 'verify': args['--verify'], 'checksum': args['--checksum'], 'retries': args['--retries'], 'retries_sleep': args['--sleep'], 'delete': args['--delete'], 'validate_identifier': True, } # Upload files. if not args['--spreadsheet']: if args['-']: local_file = TemporaryFile() # sys.stdin normally has the buffer attribute which returns bytes. # However, this might not always be the case, e.g. on mocking for test purposes. # Fall back to reading as str and encoding back to bytes. # Note that the encoding attribute might also be None. In that case, fall back to # locale.getpreferredencoding, the default of io.TextIOWrapper and open(). if hasattr(sys.stdin, 'buffer'): def read(): return sys.stdin.buffer.read(1048576) else: encoding = sys.stdin.encoding or getpreferredencoding(False) def read(): return sys.stdin.read(1048576).encode(encoding) while True: data = read() if not data: break local_file.write(data) local_file.seek(0) else: local_file = args['<file>'] # Properly expand a period to the contents of the current working directory. if '.' in local_file: local_file = [p for p in local_file if p != '.'] local_file = os.listdir('.') + local_file if isinstance(local_file, (list, tuple, set)) and args['--remote-name']: local_file = local_file[0] if args['--remote-name']: files = {args['--remote-name']: local_file} elif args['--keep-directories']: files = {f: f for f in local_file} else: files = local_file for _r in _upload_files(item, files, upload_kwargs): if args['--debug']: break if (not _r.status_code) or (not _r.ok): ERRORS = True else: if args['--open-after-upload']: url = f'{session.protocol}//{session.host}/details/{item.identifier}' webbrowser.open_new_tab(url) # Bulk upload using spreadsheet. else: # Use the same session for each upload request. with open(args['--spreadsheet'], newline='', encoding='utf-8-sig') as csvfp: spreadsheet = csv.DictReader(csvfp) prev_identifier = None for row in spreadsheet: for metadata_key in row: if not is_valid_metadata_key(metadata_key): print(f'error: "{metadata_key}" is not a valid metadata key.', file=sys.stderr) sys.exit(1) upload_kwargs_copy = deepcopy(upload_kwargs) if row.get('REMOTE_NAME'): local_file = {row['REMOTE_NAME']: row['file']} del row['REMOTE_NAME'] elif args['--keep-directories']: local_file = {row['file']: row['file']} else: local_file = row['file'] identifier = row.get('item', row.get('identifier')) if not identifier: if not prev_identifier: print('error: no identifier column on spreadsheet.', file=sys.stderr) sys.exit(1) identifier = prev_identifier del row['file'] if 'identifier' in row: del row['identifier'] if 'item' in row: del row['item'] item = session.get_item(identifier) # TODO: Clean up how indexed metadata items are coerced # into metadata. md_args = [f'{k.lower()}:{v}' for (k, v) in row.items() if v] metadata = get_args_dict(md_args) upload_kwargs_copy['metadata'].update(metadata) r = _upload_files(item, local_file, upload_kwargs_copy, prev_identifier, session) for _r in r: if args['--debug']: break if (not _r.status_code) or (not _r.ok): ERRORS = True else: if args['--open-after-upload']: url = f'{session.protocol}//{session.host}/details/{identifier}' webbrowser.open_new_tab(url) prev_identifier = identifier if ERRORS: sys.exit(1)
14,533
Python
.py
299
36.501672
96
0.548244
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,422
ia_metadata.py
jjjake_internetarchive/internetarchive/cli/ia_metadata.py
# # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2021 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Retrieve and modify Archive.org metadata. usage: ia metadata <identifier>... [--exists | --formats] [--header=<key:value>...] ia metadata <identifier>... --modify=<key:value>... [--target=<target>] [--priority=<priority>] [--header=<key:value>...] [--timeout=<value>] [--expect=<key:value>...] ia metadata <identifier>... --remove=<key:value>... [--priority=<priority>] [--header=<key:value>...] [--timeout=<value>] [--expect=<key:value>...] ia metadata <identifier>... [--append=<key:value>... | --append-list=<key:value>...] [--priority=<priority>] [--target=<target>] [--header=<key:value>...] [--timeout=<value>] [--expect=<key:value>...] ia metadata <identifier>... --insert=<key:value>... [--priority=<priority>] [--target=<target>] [--header=<key:value>...] [--timeout=<value>] [--expect=<key:value>...] ia metadata --spreadsheet=<metadata.csv> [--priority=<priority>] [--modify=<key:value>...] [--header=<key:value>...] [--timeout=<value>] [--expect=<key:value>...] ia metadata --help options: -h, --help -m, --modify=<key:value> Modify the metadata of an item. -H, --header=<key:value>... S3 HTTP headers to send with your request. -t, --target=<target> The metadata target to modify. -a, --append=<key:value>... Append a string to a metadata element. -A, --append-list=<key:value>... Append a field to a metadata element. -i, --insert=<key:value>... Insert a value into a multi-value field given an index (e.g. `--insert=collection[0]:foo`). -E, --expect=<key:value>... Test an expectation server-side before applying patch to item metadata. -s, --spreadsheet=<metadata.csv> Modify metadata in bulk using a spreadsheet as input. -e, --exists Check if an item exists -F, --formats Return the file-formats the given item contains. -p, --priority=<priority> Set the task priority. -r, --remove=<key:value>... Remove <key:value> from a metadata element. Works on both single and multi-field metadata elements. --timeout=<value> Set a timeout for metadata writes. """ from __future__ import annotations import csv import os import sys from collections import defaultdict from copy import copy from typing import Mapping from docopt import docopt, printable_usage from requests import Response from schema import And, Or, Schema, SchemaError, Use # type: ignore[import] from internetarchive import item, session from internetarchive.cli.argparser import ( get_args_dict, get_args_dict_many_write, get_args_header_dict, ) from internetarchive.exceptions import ItemLocateError from internetarchive.utils import json def modify_metadata(item: item.Item, metadata: Mapping, args: Mapping) -> Response: append = bool(args['--append']) expect = get_args_dict(args['--expect']) append_list = bool(args['--append-list']) insert = bool(args['--insert']) try: r = item.modify_metadata(metadata, target=args['--target'], append=append, expect=expect, priority=args['--priority'], append_list=append_list, headers=args['--header'], insert=insert, timeout=args['--timeout'], refresh=False) assert isinstance(r, Response) # mypy: modify_metadata() -> Request | Response except ItemLocateError as exc: print(f'{item.identifier} - error: {exc}', file=sys.stderr) sys.exit(1) if not r.json()['success']: error_msg = r.json()['error'] etype = 'warning' if 'no changes' in r.text else 'error' print(f'{item.identifier} - {etype} ({r.status_code}): {error_msg}', file=sys.stderr) return r print(f'{item.identifier} - success: {r.json()["log"]}', file=sys.stderr) return r def remove_metadata(item: item.Item, metadata: Mapping, args: Mapping) -> Response: md: dict[str, list | str] = defaultdict(list) for key in metadata: src_md = copy(item.metadata.get(key)) if not src_md: print(f'{item.identifier}/metadata/{key} does not exist, skipping.', file=sys.stderr) continue if key == 'collection': _col = copy(metadata[key]) _src_md = copy(src_md) if not isinstance(_col, list): _col = [_col] if not isinstance(_src_md, list): _src_md = [_src_md] for c in _col: if c not in _src_md: r = item.remove_from_simplelist(c, 'holdings') j = r.json() if j.get('success'): print(f'{item.identifier} - success: {item.identifier} no longer in {c}', file=sys.stderr) sys.exit(0) elif j.get('error', '').startswith('no row to delete for'): print(f'{item.identifier} - success: {item.identifier} no longer in {c}', file=sys.stderr) sys.exit(0) else: print(f'{item.identifier} - error: {j.get("error")}', file=sys.stderr) sys.exit(1) if not isinstance(src_md, list): if key == 'subject': src_md = src_md.split(';') elif key == 'collection': print(f'{item.identifier} - error: all collections would be removed, ' 'not submitting task.', file=sys.stderr) sys.exit(1) if src_md == metadata[key]: md[key] = 'REMOVE_TAG' continue for x in src_md: if isinstance(metadata[key], list): if x not in metadata[key]: md[key].append(x) # type: ignore else: if x != metadata[key]: md[key].append(x) # type: ignore if len(md[key]) == len(src_md): del md[key] # Workaround to avoid empty lists or strings as values. # TODO: Shouldn't the metadata api handle this? if len(src_md) == 1 and metadata[key] in src_md: md[key] = 'REMOVE_TAG' if md.get('collection') == []: print(f'{item.identifier} - error: all collections would be removed, not submitting task.', file=sys.stderr) sys.exit(1) elif not md: print(f'{item.identifier} - warning: nothing needed to be removed.', file=sys.stderr) sys.exit(0) r = modify_metadata(item, md, args) return r def main(argv: dict, session: session.ArchiveSession) -> None: args = docopt(__doc__, argv=argv) # Validate args. s = Schema({ str: bool, '<identifier>': list, '--modify': list, '--expect': list, '--header': Or(None, And(Use(get_args_header_dict), dict), error='--header must be formatted as --header="key:value"'), '--append': list, '--append-list': list, '--insert': list, '--remove': list, '--spreadsheet': Or(None, And(lambda f: os.path.exists(f), error='<file> should be a readable file or directory.')), '--target': Or(None, str), '--priority': Or(None, Use(int, error='<priority> should be an integer.')), '--timeout': Or(None, str), }) try: args = s.validate(args) except SchemaError as exc: print(f'{exc}\n{printable_usage(__doc__)}', file=sys.stderr) sys.exit(1) formats = set() responses: list[bool | Response] = [] for i, identifier in enumerate(args['<identifier>']): item = session.get_item(identifier) # Check existence of item. if args['--exists']: if item.exists: responses.append(True) print(f'{identifier} exists', file=sys.stderr) else: responses.append(False) print(f'{identifier} does not exist', file=sys.stderr) if (i + 1) == len(args['<identifier>']): if all(r is True for r in responses): sys.exit(0) else: sys.exit(1) # Modify metadata. elif (args['--modify'] or args['--append'] or args['--append-list'] or args['--remove'] or args['--insert']): if args['--modify']: metadata_args = args['--modify'] elif args['--append']: metadata_args = args['--append'] elif args['--append-list']: metadata_args = args['--append-list'] elif args['--insert']: metadata_args = args['--insert'] if args['--remove']: metadata_args = args['--remove'] try: metadata = get_args_dict(metadata_args) if any('/' in k for k in metadata): metadata = get_args_dict_many_write(metadata) except ValueError: print('error: The value of --modify, --remove, --append, --append-list ' 'or --insert is invalid. It must be formatted as: ' '--modify=key:value', file=sys.stderr) sys.exit(1) if args['--remove']: responses.append(remove_metadata(item, metadata, args)) else: responses.append(modify_metadata(item, metadata, args)) if (i + 1) == len(args['<identifier>']): if all(r.status_code == 200 for r in responses): # type: ignore sys.exit(0) else: for r in responses: assert isinstance(r, Response) if r.status_code == 200: continue # We still want to exit 0 if the non-200 is a # "no changes to xml" error. elif 'no changes' in r.text: continue else: sys.exit(1) # Get metadata. elif args['--formats']: for f in item.get_files(): formats.add(f.format) if (i + 1) == len(args['<identifier>']): print('\n'.join(formats)) # Dump JSON to stdout. else: metadata_str = json.dumps(item.item_metadata) print(metadata_str) # Edit metadata for items in bulk, using a spreadsheet as input. if args['--spreadsheet']: if not args['--priority']: args['--priority'] = -5 with open(args['--spreadsheet'], newline='', encoding='utf-8-sig') as csvfp: spreadsheet = csv.DictReader(csvfp) responses = [] for row in spreadsheet: if not row['identifier']: continue item = session.get_item(row['identifier']) if row.get('file'): del row['file'] metadata = {k.lower(): v for k, v in row.items() if v} responses.append(modify_metadata(item, metadata, args)) if all(r.status_code == 200 for r in responses): # type: ignore sys.exit(0) else: for r in responses: assert isinstance(r, Response) if r.status_code == 200: continue # We still want to exit 0 if the non-200 is a # "no changes to xml" error. elif 'no changes' in r.text: continue else: sys.exit(1)
13,199
Python
.py
279
34.308244
99
0.524825
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,423
ia_configure.py
jjjake_internetarchive/internetarchive/cli/ia_configure.py
# # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2019 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Configure 'ia' with your Archive.org credentials. usage: ia configure ia configure --username=<username> --password=<password> ia configure --print-cookies ia configure --netrc ia configure [--help] options: -h, --help -u, --username=<username> Provide username as an option rather than providing it interactively. -p, --password=<password> Provide password as an option rather than providing it interactively. -n, --netrc Use netrc file for login. -c, --print-cookies Print archive.org logged-in-* cookies. """ from __future__ import annotations import netrc import sys from docopt import docopt from internetarchive import ArchiveSession, configure from internetarchive.exceptions import AuthenticationError def main(argv: list[str], session: ArchiveSession) -> None: args = docopt(__doc__, argv=argv) if args['--print-cookies']: user = session.config.get('cookies', {}).get('logged-in-user') sig = session.config.get('cookies', {}).get('logged-in-sig') if not user or not sig: if not user and not sig: print('error: "logged-in-user" and "logged-in-sig" cookies ' 'not found in config file, try reconfiguring.', file=sys.stderr) elif not user: print('error: "logged-in-user" cookie not found in config file, ' 'try reconfiguring.', file=sys.stderr) elif not sig: print('error: "logged-in-sig" cookie not found in config file, ' 'try reconfiguring.', file=sys.stderr) sys.exit(1) print(f'logged-in-user={user}; logged-in-sig={sig}') sys.exit() try: # CLI params. if args['--username'] and args['--password']: config_file_path = configure(args['--username'], args['--password'], config_file=session.config_file, host=session.host) print(f'Config saved to: {config_file_path}', file=sys.stderr) # Netrc elif args['--netrc']: print("Configuring 'ia' with netrc file...", file=sys.stderr) try: n = netrc.netrc() except netrc.NetrcParseError as exc: print('error: netrc.netrc() cannot parse your .netrc file.', file=sys.stderr) sys.exit(1) username, _, password = n.hosts['archive.org'] config_file_path = configure(username, password or "", config_file=session.config_file, host=session.host) print(f'Config saved to: {config_file_path}', file=sys.stderr) # Interactive input. else: print("Enter your Archive.org credentials below to configure 'ia'.\n") config_file_path = configure(config_file=session.config_file, host=session.host) print(f'\nConfig saved to: {config_file_path}') except AuthenticationError as exc: print(f'\nerror: {exc}', file=sys.stderr) sys.exit(1)
4,133
Python
.py
88
36.170455
93
0.598661
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,424
ia_download.py
jjjake_internetarchive/internetarchive/cli/ia_download.py
# # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2021 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Download files from Archive.org. usage: ia download <identifier> [<file>]... [options]... ia download --itemlist=<file> [options]... ia download --search=<query> [options]... ia download --help options: -h, --help -q, --quiet Turn off ia's output [default: False]. -d, --dry-run Print URLs to stdout and exit. -i, --ignore-existing Clobber files already downloaded. -C, --checksum Skip files based on checksum [default: False]. -R, --retries=<retries> Set number of retries to <retries> [default: 5]. -I, --itemlist=<file> Download items from a specified file. Itemlists should be a plain text file with one identifier per line. -S, --search=<query> Download items returned from a specified search query. -P, --search-parameters=<key:value>... Download items returned from a specified search query. -g, --glob=<pattern> Only download files whose filename matches the given glob pattern. -e, --exclude=<pattern> Exclude files whose filename matches the given glob pattern. -f, --format=<format>... Only download files of the specified format. Use this option multiple times to download multiple formats. You can use the following command to retrieve a list of file formats contained within a given item: ia metadata --formats <identifier> --checksum-archive Skip files based on _checksum_archive.txt [default: False]. --on-the-fly Download on-the-fly files, as well as other matching files. on-the-fly files include derivative EPUB, MOBI and DAISY files [default: False]. --no-directories Download files into working directory. Do not create item directories. --destdir=<dir> The destination directory to download files and item directories to. -s, --stdout Write file contents to stdout. --no-change-timestamp Don't change the timestamp of downloaded files to reflect the source material. -p, --parameters=<key:value>... Parameters to send with your query (e.g. `cnt=0`). -a, --download-history Also download files from the history directory. --source=<val>... Filter files based on their source value in files.xml (i.e. `original`, `derivative`, `metadata`). --exclude-source=<val>... Filter files based on their source value in files.xml (i.e. `original`, `derivative`, `metadata`). -t, --timeout=<val> Set a timeout for download requests. This sets both connect and read timeout. """ from __future__ import annotations import ast import os import sys from os.path import exists as dir_exists from typing import TextIO from docopt import docopt, printable_usage from schema import And, Or, Schema, SchemaError, Use # type: ignore[import] from internetarchive import ArchiveSession from internetarchive.cli.argparser import get_args_dict from internetarchive.files import File from internetarchive.search import Search def main(argv, session: ArchiveSession) -> None: args = docopt(__doc__, argv=argv) # Validation error messages. destdir_msg = '--destdir must be a valid path to a directory.' itemlist_msg = '--itemlist must be a valid path to an existing file.' timeout_msg = '--timeout must be an int or float.' # Validate args. s = Schema({ str: Use(bool), '--destdir': Or([], And(Use(lambda d: d[0]), dir_exists), error=destdir_msg), '--format': list, '--glob': Use(lambda item: item[0] if item else None), '--exclude': Use(lambda item: item[0] if item else None), '<file>': list, '--search': Or(str, None), '--itemlist': Or(None, And(lambda f: os.path.isfile(f)), error=itemlist_msg), '<identifier>': Or(str, None), '--retries': Use(lambda x: x[0]), '--search-parameters': Use(lambda x: get_args_dict(x, query_string=True)), '--on-the-fly': Use(bool), '--no-change-timestamp': Use(bool), '--download-history': Use(bool), '--parameters': Use(lambda x: get_args_dict(x, query_string=True)), '--source': list, '--exclude-source': list, '--timeout': Or([], And(Use(lambda t: ast.literal_eval(t[0])), Or(int, float), error=timeout_msg)) }) try: args = s.validate(args) if args['--glob'] and args['--format']: raise SchemaError(None, '--glob and --format cannot be used together.') elif args['--exclude'] and args['--format']: raise SchemaError(None, '--exclude and --format cannot be used together.') elif args['--exclude'] and not args['--glob']: raise SchemaError(None, '--exclude should only be used in conjunction with --glob.') except SchemaError as exc: print(f'{exc}\n{printable_usage(__doc__)}', file=sys.stderr) sys.exit(1) retries = int(args['--retries']) ids: list[File | str] | Search | TextIO if args['--itemlist']: with open(args['--itemlist']) as fp: ids = [x.strip() for x in fp] total_ids = len(ids) elif args['--search']: try: _search = session.search_items(args['--search'], params=args['--search-parameters']) total_ids = _search.num_found if total_ids == 0: print(f'error: the query "{args["--search"]}" returned no results', file=sys.stderr) sys.exit(1) ids = _search except ValueError as e: print(f'error: {e}', file=sys.stderr) sys.exit(1) # Download specific files. if args['<identifier>'] and args['<identifier>'] != '-': if '/' in args['<identifier>']: identifier = args['<identifier>'].split('/')[0] files = ['/'.join(args['<identifier>'].split('/')[1:])] else: identifier = args['<identifier>'] files = args['<file>'] total_ids = 1 ids = [identifier] elif args['<identifier>'] == '-': total_ids = 1 ids = sys.stdin files = None else: files = None errors = [] for i, identifier in enumerate(ids): try: identifier = identifier.strip() except AttributeError: identifier = identifier.get('identifier') if total_ids > 1: item_index = f'{i + 1}/{total_ids}' else: item_index = None try: item = session.get_item(identifier) except Exception as exc: print(f'{identifier}: failed to retrieve item metadata - errors', file=sys.stderr) raise if 'You are attempting to make an HTTPS' in str(exc): print(f'\n{exc}', file=sys.stderr) sys.exit(1) else: continue # Otherwise, download the entire item. ignore_history_dir = True if not args['--download-history'] else False _errors = item.download( files=files, formats=args['--format'], glob_pattern=args['--glob'], exclude_pattern=args['--exclude'], dry_run=args['--dry-run'], verbose=not args['--quiet'], ignore_existing=args['--ignore-existing'], checksum=args['--checksum'], checksum_archive=args['--checksum-archive'], destdir=args['--destdir'], no_directory=args['--no-directories'], retries=retries, item_index=item_index, ignore_errors=True, on_the_fly=args['--on-the-fly'], no_change_timestamp=args['--no-change-timestamp'], params=args['--parameters'], ignore_history_dir=ignore_history_dir, source=args['--source'], exclude_source=args['--exclude-source'], stdout=args['--stdout'], timeout=args['--timeout'], ) if _errors: errors.append(_errors) if errors: # TODO: add option for a summary/report. sys.exit(1) else: sys.exit(0)
10,057
Python
.py
204
37.857843
102
0.546527
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,425
ia_delete.py
jjjake_internetarchive/internetarchive/cli/ia_delete.py
# # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2019 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Delete files from Archive.org. usage: ia delete <identifier> <file>... [options]... ia delete <identifier> [options]... ia delete --help options: -h, --help -q, --quiet Print status to stdout. -c, --cascade Delete all files associated with the specified file, including upstream derivatives and the original. file. -H, --header=<key:value>... S3 HTTP headers to send with your request. -a, --all Delete all files in the given item (Note: Some files, such as <identifier>_meta.xml and <identifier>_files.xml, cannot be deleted) -d, --dry-run Output files to be deleted to stdout, but don't actually delete. -g, --glob=<pattern> Only delete files matching the given pattern. -f, --format=<format>... Only only delete files matching the specified format(s). -R, --retries=<i> Number of times to retry if S3 returns a 503 SlowDown error [default: 2]. --no-backup Turn off archive.org backups. Clobbered files will not be saved to history/files/$key.~N~ [default: True]. """ import sys import requests.exceptions from docopt import docopt, printable_usage from schema import And, Or, Schema, SchemaError, Use # type: ignore[import] from internetarchive import ArchiveSession from internetarchive.cli.argparser import convert_str_list_to_unicode, get_args_dict from internetarchive.utils import get_s3_xml_text def main(argv, session: ArchiveSession) -> None: args = docopt(__doc__, argv=argv) # Validation error messages. invalid_id_msg = ('<identifier> should be between 3 and 80 characters in length, and ' 'can only contain alphanumeric characters, underscores ( _ ), or ' 'dashes ( - )') # Validate args. s = Schema({ str: Use(bool), '<file>': list, '--format': list, '--header': Or(None, And(Use(get_args_dict), dict), error='--header must be formatted as --header="key:value"'), '--glob': list, 'delete': bool, '--retries': Use(lambda i: int(i[0])), '<identifier>': str, }) try: args = s.validate(args) except SchemaError as exc: print(f'{exc}\n{printable_usage(__doc__)}', file=sys.stderr) sys.exit(1) verbose = True if not args['--quiet'] else False item = session.get_item(args['<identifier>']) if not item.exists: print('{0}: skipping, item does\'t exist.', file=sys.stderr) # Files that cannot be deleted via S3. no_delete = ['_meta.xml', '_files.xml', '_meta.sqlite'] # Add keep-old-version by default. if not args['--header'].get('x-archive-keep-old-version') and not args['--no-backup']: args['--header']['x-archive-keep-old-version'] = '1' if verbose: print(f'Deleting files from {item.identifier}', file=sys.stderr) if args['--all']: files = list(item.get_files()) args['--cascade'] = True elif args['--glob']: files = item.get_files(glob_pattern=args['--glob']) elif args['--format']: files = item.get_files(formats=args['--format']) else: fnames = [] if args['<file>'] == ['-']: fnames = [f.strip() for f in sys.stdin] else: fnames = [f.strip() for f in args['<file>']] files = list(item.get_files(fnames)) if not files: print(' warning: no files found, nothing deleted.', file=sys.stderr) sys.exit(1) errors = False for f in files: if not f: if verbose: print(f' error: "{f.name}" does not exist', file=sys.stderr) errors = True if any(f.name.endswith(s) for s in no_delete): continue if args['--dry-run']: print(f' will delete: {item.identifier}/{f.name}', file=sys.stderr) continue try: resp = f.delete(verbose=verbose, cascade_delete=args['--cascade'], headers=args['--header'], retries=args['--retries']) except requests.exceptions.RetryError as e: print(f' error: max retries exceeded for {f.name}', file=sys.stderr) errors = True continue if resp.status_code != 204: errors = True msg = get_s3_xml_text(resp.content) print(f' error: {msg} ({resp.status_code})', file=sys.stderr) continue if errors is True: sys.exit(1)
5,652
Python
.py
127
35.417323
90
0.586558
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,426
__init__.py
jjjake_internetarchive/internetarchive/cli/__init__.py
# # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2016, 2021 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ internetarchive.cli ~~~~~~~~~~~~~~~~~~~ :copyright: (C) 2012-2016, 2021 by Internet Archive. :license: AGPL 3, see LICENSE for more details. """ from internetarchive.cli import ( argparser, ia, ia_configure, ia_delete, ia_download, ia_list, ia_metadata, ia_search, ia_tasks, ia_upload, ) __all__ = [ 'ia', 'ia_configure', 'ia_delete', 'ia_download', 'ia_list', 'ia_metadata', 'ia_search', 'ia_tasks', 'ia_upload', 'argparser', ]
1,297
Python
.py
47
24.829787
74
0.705694
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,427
ia_copy.py
jjjake_internetarchive/internetarchive/cli/ia_copy.py
# # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2021 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Copy files in archive.org items. usage: ia copy <src-identifier>/<src-file> <dest-identifier>/<dest-file> [options]... ia copy --help options: -h, --help -m, --metadata=<key:value>... Metadata to add to your new item, if you are moving the file to a new item. --replace-metadata Only use metadata specified as argument, do not copy any from the source item. -H, --header=<key:value>... S3 HTTP headers to send with your request. --ignore-file-metadata Do not copy file metadata. -n, --no-derive Do not derive uploaded files. --no-backup Turn off archive.org backups. Clobbered files will not be saved to history/files/$key.~N~ [default: True]. """ from __future__ import annotations import sys from urllib.parse import quote from docopt import docopt, printable_usage from requests import Response from schema import And, Or, Schema, SchemaError, Use # type: ignore[import] import internetarchive as ia from internetarchive.cli.argparser import get_args_dict from internetarchive.utils import get_s3_xml_text, merge_dictionaries def assert_src_file_exists(src_location: str) -> bool: assert SRC_ITEM.exists # type: ignore global SRC_FILE src_filename = src_location.split('/', 1)[-1] SRC_FILE = SRC_ITEM.get_file(src_filename) # type: ignore assert SRC_FILE.exists # type: ignore return True def main( argv: list[str] | None, session: ia.session.ArchiveSession, cmd: str = 'copy' ) -> tuple[Response, ia.files.File]: args = docopt(__doc__, argv=argv) src_path = args['<src-identifier>/<src-file>'] dest_path = args['<dest-identifier>/<dest-file>'] # If src == dest, file gets deleted! try: assert src_path != dest_path except AssertionError: print('error: The source and destination files cannot be the same!', file=sys.stderr) sys.exit(1) global SRC_ITEM SRC_ITEM = session.get_item(src_path.split('/')[0]) # type: ignore # Validate args. s = Schema({ str: Use(bool), '<src-identifier>/<src-file>': And(str, And(And(str, lambda x: '/' in x, error='Destination not formatted correctly. See usage example.'), assert_src_file_exists, error=( f'https://{session.host}/download/{src_path} does not exist. ' 'Please check the identifier and filepath and retry.'))), '<dest-identifier>/<dest-file>': And(str, lambda x: '/' in x, error='Destination not formatted correctly. See usage example.'), '--metadata': Or(None, And(Use(get_args_dict), dict), error='--metadata must be formatted as --metadata="key:value"'), '--replace-metadata': Use(bool), '--header': Or(None, And(Use(get_args_dict), dict), error='--header must be formatted as --header="key:value"'), '--ignore-file-metadata': Use(bool), }) try: args = s.validate(args) except SchemaError as exc: # This module is sometimes called by other modules. # Replace references to 'ia copy' in ___doc__ to 'ia {cmd}' for clarity. usage = printable_usage(__doc__.replace('ia copy', f'ia {cmd}')) print(f'{exc}\n{usage}', file=sys.stderr) sys.exit(1) args['--header']['x-amz-copy-source'] = f'/{quote(src_path)}' # Copy the old metadata verbatim if no additional metadata is supplied, # else combine the old and the new metadata in a sensible manner. if args['--metadata'] or args['--replace-metadata']: args['--header']['x-amz-metadata-directive'] = 'REPLACE' else: args['--header']['x-amz-metadata-directive'] = 'COPY' # New metadata takes precedence over old metadata. if not args['--replace-metadata']: args['--metadata'] = merge_dictionaries(SRC_ITEM.metadata, # type: ignore args['--metadata']) # File metadata is copied by default but can be dropped. file_metadata = None if args['--ignore-file-metadata'] else SRC_FILE.metadata # type: ignore # Add keep-old-version by default. if not args['--header'].get('x-archive-keep-old-version') and not args['--no-backup']: args['--header']['x-archive-keep-old-version'] = '1' url = f'{session.protocol}//s3.us.archive.org/{quote(dest_path)}' queue_derive = True if args['--no-derive'] is False else False req = ia.iarequest.S3Request(url=url, method='PUT', metadata=args['--metadata'], file_metadata=file_metadata, headers=args['--header'], queue_derive=queue_derive, access_key=session.access_key, secret_key=session.secret_key) p = req.prepare() r = session.send(p) if r.status_code != 200: try: msg = get_s3_xml_text(r.text) except Exception as e: msg = r.text print(f'error: failed to {cmd} "{src_path}" to "{dest_path}" - {msg}', file=sys.stderr) sys.exit(1) elif cmd == 'copy': print(f'success: copied "{src_path}" to "{dest_path}".', file=sys.stderr) return (r, SRC_FILE) # type: ignore
6,307
Python
.py
128
40.648438
97
0.615909
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,428
ia.py
jjjake_internetarchive/internetarchive/cli/ia.py
#!/usr/bin/env python # # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2019 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """A command line interface to Archive.org. usage: ia [--help | --version] ia [--config-file FILE] [--log | --debug] [--insecure] [--host HOST] <command> [<args>]... options: -h, --help -v, --version -c, --config-file FILE Use FILE as config file. (Can also be set with the IA_CONFIG_FILE environment variable. The option takes precedence when both are used.) -l, --log Turn on logging [default: False]. -d, --debug Turn on verbose logging [default: False]. -i, --insecure Use HTTP for all requests instead of HTTPS [default: false] -H, --host HOST Host to use for requests (doesn't work for requests made to s3.us.archive.org) [default: archive.org] commands: help Retrieve help for subcommands. configure Configure `ia`. metadata Retrieve and modify metadata for items on Archive.org. upload Upload items to Archive.org. download Download files from Archive.org. delete Delete files from Archive.org. search Search Archive.org. tasks Retrieve information about your Archive.org catalog tasks. list List files in a given item. copy Copy files in archive.org items. move Move/rename files in archive.org items. reviews Submit/modify reviews for archive.org items. Documentation for 'ia' is available at: https://archive.org/services/docs/api/internetarchive/cli.html See 'ia help <command>' for help on a specific command. """ from __future__ import annotations import difflib import errno import os import sys from docopt import docopt, printable_usage if sys.version_info < (3, 10): from importlib_metadata import entry_points # type: ignore[import] else: from importlib.metadata import entry_points from schema import Or, Schema, SchemaError # type: ignore[import] from internetarchive import __version__ from internetarchive.api import get_session from internetarchive.utils import suppress_keyboard_interrupt_message suppress_keyboard_interrupt_message() cmd_aliases = { 'co': 'configure', 'md': 'metadata', 'up': 'upload', 'do': 'download', 'rm': 'delete', 'se': 'search', 'ta': 'tasks', 'ls': 'list', 'cp': 'copy', 'mv': 'move', 're': 'reviews', } def load_ia_module(cmd: str): """Dynamically import ia module.""" try: if cmd in list(cmd_aliases.keys()) + list(cmd_aliases.values()): _module = f'internetarchive.cli.ia_{cmd}' return __import__(_module, fromlist=['internetarchive.cli']) else: _module = f'ia_{cmd}' for ep in entry_points(group='internetarchive.cli.plugins'): if ep.name == _module: return ep.load() raise ImportError except (ImportError): print(f"error: '{cmd}' is not an ia command! See 'ia help'", file=sys.stderr) matches = '\t'.join(difflib.get_close_matches(cmd, cmd_aliases.values())) if matches: print(f'\nDid you mean one of these?\n\t{matches}', file=sys.stderr) sys.exit(127) def main() -> None: """This is the CLI driver for ia-wrapper.""" args = docopt(__doc__, version=__version__, options_first=True) # Validate args. s = Schema({ str: bool, '--config-file': Or(None, str), '--host': Or(None, str), '<args>': list, '<command>': Or(str, lambda _: 'help'), }) try: args = s.validate(args) except SchemaError as exc: print(f'{exc}\n{printable_usage(__doc__)}', file=sys.stderr) sys.exit(1) # Get subcommand. cmd = args['<command>'] if cmd in cmd_aliases: cmd = cmd_aliases[cmd] if (cmd == 'help') or (not cmd): if not args['<args>']: sys.exit(print(__doc__.strip(), file=sys.stderr)) else: ia_module = load_ia_module(args['<args>'][0]) sys.exit(print(ia_module.__doc__.strip(), file=sys.stderr)) if cmd != 'configure' and args['--config-file']: if not os.path.isfile(args['--config-file']): print(f'--config-file should be a readable file.\n{printable_usage(__doc__)}', file=sys.stderr) sys.exit(1) argv = [cmd] + args['<args>'] config: dict[str, dict] = {} if args['--log']: config['logging'] = {'level': 'INFO'} elif args['--debug']: config['logging'] = {'level': 'DEBUG'} if args['--insecure']: config['general'] = {'secure': False} if args['--host']: if config.get('general'): config['general']['host'] = args['--host'] else: config['general'] = {'host': args['--host']} session = get_session(config_file=args['--config-file'], config=config, debug=args['--debug']) ia_module = load_ia_module(cmd) try: sys.exit(ia_module.main(argv, session)) except OSError as e: # Handle Broken Pipe errors. if e.errno == errno.EPIPE: sys.stderr.close() sys.stdout.close() sys.exit(0) else: raise if __name__ == '__main__': main()
6,139
Python
.py
158
32.132911
90
0.614415
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,429
ia_list.py
jjjake_internetarchive/internetarchive/cli/ia_list.py
# # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2019 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """List files in a given item. usage: ia list [-v] [--glob=<pattern>] [--location] [--format=<format>...] [--columns <column1,column2> | --all] <identifier> options: -h, --help -v, --verbose Print column headers. [default: False] -a, --all List all information available for files. -l, --location Print full URL for each file. -c, --columns=<name,size> List specified file information. [default: name] -g, --glob=<pattern> Only return patterns match the given pattern. -f, --format=<format> Return files matching <format>. """ import csv import sys from fnmatch import fnmatch from itertools import chain from docopt import docopt from internetarchive import ArchiveSession def main(argv, session: ArchiveSession) -> None: args = docopt(__doc__, argv=argv) item = session.get_item(args['<identifier>']) files = item.files if args.get('--all'): columns = list(set(chain.from_iterable(k for k in files))) else: columns = args['--columns'].split(',') # Make "name" the first column always. if 'name' in columns: columns.remove('name') columns.insert(0, 'name') dict_writer = csv.DictWriter(sys.stdout, columns, delimiter='\t', lineterminator='\n') if args.get('--glob'): patterns = args['--glob'].split('|') files = [f for f in files if any(fnmatch(f['name'], p) for p in patterns)] elif args.get('--format'): files = [f.__dict__ for f in item.get_files(formats=args['--format'])] output = [] for f in files: file_dict = {} for key, val in f.items(): if key in columns: if isinstance(val, (list, tuple, set)): val = ';'.join(val) if key == 'name' and args.get('--location'): file_dict[key] = f'https://{session.host}/download/{item.identifier}/{val}' else: file_dict[key] = val output.append(file_dict) if args['--verbose']: dict_writer.writer.writerow(columns) if all(x == {} for x in output): sys.exit(1) dict_writer.writerows(output)
3,002
Python
.py
71
36.591549
95
0.637766
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,430
ia_tasks.py
jjjake_internetarchive/internetarchive/cli/ia_tasks.py
# # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2021 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Retrieve information about your catalog tasks. For more information on how to use this command, refer to the Tasks API documentation:: https://archive.org/services/docs/api/tasks.html usage: ia tasks [--task=<task_id>...] [--get-task-log=<task_id>] [--parameter=<k:v>...] [--tab-output] ia tasks <identifier> [--parameter=<k:v>...] [--tab-output] ia tasks <identifier> --cmd=<command> [--comment=<comment>] [--task-args=<k:v>...] [--data=<k:v>...] [--tab-output] [--reduced-priority] ia tasks --get-rate-limit --cmd=<command> ia tasks --help options: -h, --help -t, --task=<task_id>... Return information about the given task. -G, --get-task-log=<task_id> Return the given tasks task log. -p, --parameter=<k:v>... URL parameters passed to catalog.php. -c, --cmd=<command> The task to submit (e.g. make_dark.php). -C, --comment=<comment> A reasonable explanation for why a task is being submitted. -T, --tab-output Output task info in tab-delimited columns. -a, --task-args=<k:v>... Args to submit to the Tasks API. -r, --reduced-priority Submit task at a reduced priority. Note that it may take a very long time for your task to run after queued when this setting is used [default: False]. -l, --get-rate-limit Get rate limit info. -d, --data=<k:v>... Additional data to send when submitting a task. examples: ia tasks nasa ia tasks nasa -p cmd:derive.php # only return derive.php tasks ia tasks -p 'args:*s3-put*' # return all S3 tasks ia tasks -p 'submitter=jake@archive.org' # return all tasks submitted by a user ia tasks --get-task-log 1178878475 # get a task log for a specific task ia tasks <id> --cmd make_undark.php --comment '<comment>' # undark item ia tasks <id> --cmd make_dark.php --comment '<comment>' # dark item ia tasks <id> --cmd fixer.php --task-args noop:1 # submit a noop fixer.php task ia tasks <id> --cmd fixer.php --task-args 'noop:1;asr:1' # submit multiple fixer ops ia tasks --get-rate-limit --cmd derive.php # Get rate-limit information for a specific command """ import sys import warnings from docopt import docopt from internetarchive import ArchiveSession from internetarchive.cli.argparser import get_args_dict from internetarchive.utils import json def main(argv, session: ArchiveSession) -> None: args = docopt(__doc__, argv=argv) # Tasks write API. if args['--cmd']: if args['--get-rate-limit']: r = session.get_tasks_api_rate_limit(args['--cmd']) print(json.dumps(r)) sys.exit(0) data = get_args_dict(args['--data'], query_string=True) task_args = get_args_dict(args['--task-args'], query_string=True) data['args'] = task_args r = session.submit_task(args['<identifier>'], args['--cmd'], comment=args['--comment'], priority=int(data.get('priority', 0)), reduced_priority=args['--reduced-priority'], data=data) j = r.json() if j.get('success'): task_log_url = j.get('value', {}).get('log') print(f'success: {task_log_url}', file=sys.stderr) sys.exit(0) elif 'already queued/running' in j.get('error', ''): print(f'success: {args["--cmd"]} task already queued/running', file=sys.stderr) sys.exit(0) else: print(f'error: {j.get("error")}', file=sys.stderr) sys.exit(1) # Tasks read API. params = get_args_dict(args['--parameter'], query_string=True) if args['<identifier>']: _params = {'identifier': args['<identifier>'], 'catalog': 1, 'history': 1} _params.update(params) params = _params elif args['--get-task-log']: log = session.get_task_log(args['--get-task-log'], params) print(log.encode('utf-8', errors='surrogateescape') .decode('utf-8', errors='replace')) sys.exit(0) queryable_params = [ 'identifier', 'task_id', 'server', 'cmd', 'args', 'submitter', 'priority', 'wait_admin', 'submittime', ] if not (args['<identifier>'] or params.get('task_id')): _params = {'catalog': 1, 'history': 0} _params.update(params) params = _params if not any(x in params for x in queryable_params): _params = {'submitter': session.user_email, 'catalog': 1, 'history': 0, 'summary': 0} _params.update(params) params = _params if args['--tab-output']: warn_msg = ('tab-delimited output will be removed in a future release. ' 'Please switch to the default JSON output.') warnings.warn(warn_msg, stacklevel=2) for t in session.get_tasks(params=params): # Legacy support for tab-delimted output. # Mypy is confused by CatalogTask members being created from kwargs if args['--tab-output']: color = t.color if t.color else 'done' task_args = '\t'.join([f'{k}={v}' for k, v in t.args.items()]) # type: ignore output = '\t'.join([str(x) for x in [ # type: ignore t.identifier, # type: ignore t.task_id, # type: ignore t.server, # type: ignore t.submittime, # type: ignore t.cmd, # type: ignore color, # type: ignore t.submitter, # type: ignore task_args, ] if x]) print(output, flush=True) else: print(t.json(), flush=True)
6,838
Python
.py
147
37.156463
99
0.582859
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,431
conf.py
jjjake_internetarchive/docs/source/conf.py
# # internetarchive documentation build configuration file, created by # sphinx-quickstart on Mon Sep 23 20:16:03 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys import alabaster import internetarchive from internetarchive import __version__ # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('../../')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', 'alabaster', 'sphinx_autodoc_typehints', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'internetarchive' copyright = '2015, Internet Archive' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = __version__ # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns: list[str] = [] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). add_module_names = False # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme_path = [alabaster.get_path()] html_theme = 'alabaster' html_sidebars = { '**': [ 'sidebarlogo.html', 'about.html', 'navigation.html', 'usefullinks.html', 'searchbox.html', ] } html_theme_options = { 'github_user': 'jjjake', 'github_repo': 'internetarchive', 'github_button': True, 'show_powered_by': 'false', 'sidebar_width': '200px', } # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = '_static/ia.png' # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'internetarchivedoc' # -- Options for LaTeX output --------------------------------------------- latex_elements: dict[str, str] = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto/manual]). latex_documents = [ ('index', 'internetarchive.tex', 'internetarchive Documentation', 'Jacob M. Johnson', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'internetarchive', 'internetarchive Documentation', ['Jacob M. Johnson'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'internetarchive', 'internetarchive Documentation', 'Jacob M. Johnson', 'internetarchive', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False #autodoc_member_order = 'bysource' intersphinx_mapping = { 'python': ('https://docs.python.org/3', None), 'requests': ('http://docs.python-requests.org/en/latest/', None) }
9,098
Python
.py
223
38.892377
79
0.724867
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,432
lint_python.yml
jjjake_internetarchive/.github/workflows/lint_python.yml
name: lint_python on: [pull_request, push] jobs: lint_python: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: cache: pip python-version: 3.x - run: pip install --upgrade pip setuptools wheel - run: pip install .[all] - run: black --check --skip-string-normalization . || true - run: ruff --format=github . # See pyproject.toml for configuration - run: pip install -r pex-requirements.txt -r tests/requirements.txt - run: mypy . # See setup.cfg for configuration - run: safety check || true # Temporary fix for https://pyup.io/v/51457/f17
681
Python
.py
18
31.722222
82
0.641026
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,433
conftest.py
jjjake_internetarchive/tests/conftest.py
import os import re import sys from subprocess import PIPE, Popen import pytest import responses from responses import RequestsMock from internetarchive import get_session from internetarchive.api import get_item from internetarchive.cli import ia from internetarchive.utils import json PROTOCOL = 'https:' BASE_URL = 'https://archive.org/' METADATA_URL = f'{BASE_URL}metadata/' ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEST_CONFIG = os.path.join(ROOT_DIR, 'tests/ia.ini') NASA_METADATA_PATH = os.path.join(ROOT_DIR, 'tests/data/metadata/nasa.json') NASA_EXPECTED_FILES = { 'globe_west_540.jpg', 'globe_west_540_thumb.jpg', 'nasa_archive.torrent', 'nasa_meta.sqlite', 'nasa_files.xml', 'nasa_meta.xml', 'nasa_reviews.xml', 'nasa_itemimage.jpg', 'globe_west_540_thumb.jpg', '__ia_thumb.jpg', } def ia_call(argv, expected_exit_code=0): # Use a test config for all `ia` tests. argv.insert(1, '--config-file') argv.insert(2, TEST_CONFIG) sys.argv = argv try: ia.main() except SystemExit as exc: exit_code = exc.code if exc.code else 0 assert exit_code == expected_exit_code def files_downloaded(path): found_files = set() try: found_files = set(os.listdir(path)) except OSError: pass return found_files def load_file(filename): with open(filename) as fh: return fh.read() def load_test_data_file(filename): return load_file(os.path.join(ROOT_DIR, 'tests/data/', filename)) def call_cmd(cmd, expected_exit_code=0): proc = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) # noqa: S602 stdout, stderr = proc.communicate() stdout = stdout.decode('utf-8').strip() stderr = stderr.decode('utf-8').strip() if proc.returncode != expected_exit_code: print(stdout) print(stderr) assert proc.returncode == expected_exit_code return (stdout, stderr) class IaRequestsMock(RequestsMock): def add_metadata_mock(self, identifier, body=None, method=responses.GET, protocol='https?', transform_body=None): url = re.compile(f'{protocol}://archive.org/metadata/{identifier}') if body is None: body = load_test_data_file(f'metadata/{identifier}.json') if transform_body: body = transform_body(body) self.add(method, url, body=body, content_type='application/json') def mock_all_downloads(self, num_calls=1, body='test content', protocol='https?'): url = re.compile(f'{protocol}://archive.org/download/.*') for _ in range(6): self.add(responses.GET, url, body=body) @pytest.fixture() def tmpdir_ch(tmpdir): tmpdir.chdir() return tmpdir @pytest.fixture() def nasa_mocker(): with IaRequestsMock() as mocker: mocker.add_metadata_mock('nasa') yield mocker @pytest.fixture() def nasa_item(): session = get_session() with IaRequestsMock() as mocker: mocker.add_metadata_mock('nasa') yield session.get_item('nasa') @pytest.fixture() def session(): return get_session(config={'s3': {'access': 'access', 'secret': 'secret'}}) @pytest.fixture() def nasa_metadata(): return json.loads(load_test_data_file('metadata/nasa.json')) # TODO: Why is this function defined twice in this file? See issue #505 @pytest.fixture() # type: ignore def nasa_item(nasa_mocker): # noqa: F811 return get_item('nasa')
3,489
Python
.py
99
30.262626
86
0.679358
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,434
test_bad_data.py
jjjake_internetarchive/tests/test_bad_data.py
from internetarchive.api import get_item from tests.conftest import IaRequestsMock def test_bad_mediatype(): # this identifier actually has this malformed data ident = 'CIA-RDP96-00789R000700210007-5' body = '{"metadata": {"mediatype":["texts","texts"]}}' with IaRequestsMock() as rsps: rsps.add_metadata_mock(ident, body=body) # should complete without error get_item(ident)
418
Python
.py
10
36.6
58
0.714286
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,435
test_api.py
jjjake_internetarchive/tests/test_api.py
import os import re import responses import urllib3 from internetarchive import ( download, get_files, get_item, get_session, modify_metadata, search_items, upload, ) from internetarchive.utils import InvalidIdentifierException, json from tests.conftest import ( NASA_METADATA_PATH, PROTOCOL, IaRequestsMock, load_file, load_test_data_file, ) TEST_SEARCH_RESPONSE = load_test_data_file('advanced_search_response.json') TEST_SCRAPE_RESPONSE = load_test_data_file('scrape_response.json') _j = json.loads(TEST_SCRAPE_RESPONSE) del _j['cursor'] _j['items'] = [{'identifier': 'nasa'}] _j['total'] = 1 TEST_SCRAPE_RESPONSE = json.dumps(_j) def test_get_session_with_config(): s = get_session(config={'s3': {'access': 'key'}, 'gengeral': {'secure': False}}) assert s.access_key == 'key' def test_get_session_with_config_file(tmpdir): tmpdir.chdir() test_conf = '[s3]\naccess = key2' with open('ia_test.ini', 'w') as fh: fh.write(test_conf) s = get_session(config_file='ia_test.ini') assert s.access_key == 'key2' def test_get_item(nasa_mocker): item = get_item('nasa') assert item.identifier == 'nasa' def test_get_item_with_config(nasa_mocker): item = get_item('nasa', config={'s3': {'access': 'key'}}) assert item.session.access_key == 'key' def test_get_item_with_config_file(tmpdir, nasa_mocker): tmpdir.chdir() test_conf = '[s3]\naccess = key2' with open('ia_test.ini', 'w') as fh: fh.write(test_conf) item = get_item('nasa', config_file='ia_test.ini') assert item.session.access_key == 'key2' def test_get_item_with_archive_session(nasa_mocker): s = get_session(config={'s3': {'access': 'key3'}}) item = get_item('nasa', archive_session=s) assert item.session.access_key == 'key3' def test_get_item_with_kwargs(): with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add_metadata_mock('nasa') item = get_item('nasa', http_adapter_kwargs={'max_retries': 13}) assert isinstance(item.session.adapters[f'{PROTOCOL}//'].max_retries, urllib3.Retry) try: get_item('nasa', request_kwargs={'timeout': .0000000000001}) except Exception as exc: assert 'timed out' in str(exc) def test_get_files(): with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add_metadata_mock('nasa') files = get_files('nasa') expected_files = { 'NASAarchiveLogo.jpg', 'globe_west_540.jpg', 'nasa_reviews.xml', 'nasa_meta.xml', 'nasa_archive.torrent', 'nasa_files.xml', } assert {f.name for f in files} == expected_files def test_get_files_with_get_item_kwargs(tmpdir): tmpdir.chdir() with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add_metadata_mock('nasa') s = get_session(config={'s3': {'access': 'key'}}) files = get_files('nasa', files='nasa_meta.xml', archive_session=s) files = list(files) assert len(files) == 1 assert files[0].name == 'nasa_meta.xml' files = get_files('nasa', files='nasa_meta.xml', config={'logging': {'level': 'INFO'}}) files = list(files) assert len(files) == 1 assert files[0].name == 'nasa_meta.xml' test_conf = '[s3]\naccess = key2' with open('ia_test.ini', 'w') as fh: fh.write(test_conf) files = get_files('nasa', files='nasa_meta.xml', config_file='ia_test.ini') files = list(files) assert len(files) == 1 assert files[0].name == 'nasa_meta.xml' files = get_files('nasa', files='nasa_meta.xml', http_adapter_kwargs={'max_retries': 3}) files = list(files) assert len(files) == 1 assert files[0].name == 'nasa_meta.xml' files = get_files('nasa', files='nasa_meta.xml', request_kwargs={'timeout': 4}) files = list(files) assert len(files) == 1 assert files[0].name == 'nasa_meta.xml' def test_get_files_non_existing(nasa_mocker): files = get_files('nasa', files='none') assert list(files) == [] def test_get_files_multiple(nasa_mocker): _files = ['nasa_meta.xml', 'nasa_files.xml'] files = get_files('nasa', files=_files) for f in files: assert f.name in _files def test_get_files_formats(): with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add_metadata_mock('nasa') files = get_files('nasa', formats='JPEG') files = list(files) assert len(files) == 1 assert files[0].name == 'globe_west_540.jpg' files = get_files('nasa', formats=['JPEG', 'Collection Header']) expected_files = { 'globe_west_540.jpg', 'NASAarchiveLogo.jpg', } assert {f.name for f in files} == expected_files def test_get_files_glob_pattern(): with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add_metadata_mock('nasa') files = get_files('nasa', glob_pattern='*torrent') files = list(files) assert len(files) == 1 assert files[0].name == 'nasa_archive.torrent' files = get_files('nasa', glob_pattern='*torrent|*jpg') expected_files = { 'globe_west_540.jpg', 'NASAarchiveLogo.jpg', 'nasa_archive.torrent', } assert {f.name for f in files} == expected_files def test_modify_metadata(): with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add(responses.GET, f'{PROTOCOL}//archive.org/metadata/nasa', body='{"metadata":{"title":"foo"}}') rsps.add(responses.POST, f'{PROTOCOL}//archive.org/metadata/nasa', body=('{"success":true,"task_id":423444944,' '"log":"https://catalogd.archive.org/log/423444944"}')) r = modify_metadata('nasa', {'foo': 1}) assert r.status_code == 200 assert r.json() == { 'task_id': 423444944, 'success': True, 'log': 'https://catalogd.archive.org/log/423444944' } def test_upload(): expected_s3_headers = { 'content-length': '7557', 'x-archive-queue-derive': '1', 'x-archive-meta00-scanner': 'uri(Internet%20Archive%20Python%20library', 'x-archive-size-hint': '7557', 'x-archive-auto-make-bucket': '1', 'authorization': 'LOW test_access:test_secret', } with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add(responses.PUT, re.compile(r'.*s3.us.archive.org/.*'), adding_headers=expected_s3_headers) rsps.add_metadata_mock('nasa') rsps.add(responses.GET, f'{PROTOCOL}//archive.org/metadata/nasa', body='{}') _responses = upload('nasa', NASA_METADATA_PATH, access_key='test_access', secret_key='test_secret') for response in _responses: req = response.request headers = {k.lower(): str(v) for k, v in req.headers.items()} scanner_header = '%20'.join( response.headers['x-archive-meta00-scanner'].split('%20')[:4]) headers['x-archive-meta00-scanner'] = scanner_header assert 'user-agent' in headers del headers['accept'] del headers['accept-encoding'] del headers['connection'] del headers['user-agent'] assert headers == expected_s3_headers assert req.url == f'{PROTOCOL}//s3.us.archive.org/nasa/nasa.json' def test_upload_validate_identifier(): try: upload('føø', NASA_METADATA_PATH, access_key='test_access', secret_key='test_secret', validate_identifier=True) raise AssertionError("Given invalid identifier was not correctly validated.") except Exception as exc: assert isinstance(exc, InvalidIdentifierException) expected_s3_headers = { 'content-length': '7557', 'x-archive-queue-derive': '1', 'x-archive-meta00-scanner': 'uri(Internet%20Archive%20Python%20library', 'x-archive-size-hint': '7557', 'x-archive-auto-make-bucket': '1', 'authorization': 'LOW test_access:test_secret', } with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add(responses.PUT, re.compile(r'.*s3.us.archive.org/.*'), adding_headers=expected_s3_headers) rsps.add_metadata_mock('nasa') rsps.add(responses.GET, f'{PROTOCOL}//archive.org/metadata/nasa', body='{}') upload('nasa', NASA_METADATA_PATH, access_key='test_access', secret_key='test_secret', validate_identifier=True) assert True def test_download(tmpdir): tmpdir.chdir() last_mod_header = {"Last-Modified": "Tue, 14 Nov 2023 20:25:48 GMT"} with IaRequestsMock() as rsps: rsps.add(responses.GET, f'{PROTOCOL}//archive.org/download/nasa/nasa_meta.xml', body='test content', adding_headers=last_mod_header) rsps.add_metadata_mock('nasa') download('nasa', 'nasa_meta.xml') p = os.path.join(str(tmpdir), 'nasa') assert len(os.listdir(p)) == 1 assert load_file('nasa/nasa_meta.xml') == 'test content' def test_search_items(session): url = f'{PROTOCOL}//archive.org/services/search/v1/scrape' p1 = { 'q': 'identifier:nasa', 'count': '10000', } p2 = p1.copy() p2['total_only'] = 'true' with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add(responses.POST, url, body=TEST_SCRAPE_RESPONSE, match=[responses.matchers.query_param_matcher(p1)]) rsps.add(responses.POST, url, body='{"items":[],"count":0,"total":1}', match=[responses.matchers.query_param_matcher(p2)], content_type='application/json; charset=UTF-8') r = search_items('identifier:nasa', archive_session=session) expected_results = [{'identifier': 'nasa'}] assert r.num_found == 1 assert iter(r).search == r assert len(iter(r)) == 1 assert len(r.iter_as_results()) == 1 assert list(r) == expected_results assert list(r.iter_as_results()) == expected_results assert r.fts == False def test_search_items_with_fields(session): _j = json.loads(TEST_SCRAPE_RESPONSE) _j['items'] = [ {'identifier': 'nasa', 'title': 'NASA Images'} ] search_response_str = json.dumps(_j) url = f'{PROTOCOL}//archive.org/services/search/v1/scrape' p1 = { 'q': 'identifier:nasa', 'count': '10000', 'fields': 'identifier,title', } p2 = { 'q': 'identifier:nasa', 'total_only': 'true', 'count': '10000', } with IaRequestsMock() as rsps: rsps.add(responses.POST, url, match=[responses.matchers.query_param_matcher(p1)], body=search_response_str) rsps.add(responses.POST, url, body='{"items":[],"count":0,"total":1}', match=[responses.matchers.query_param_matcher(p2)], content_type='application/json; charset=UTF-8') r = search_items('identifier:nasa', fields=['identifier', 'title'], archive_session=session) assert list(r) == [{'identifier': 'nasa', 'title': 'NASA Images'}] def test_search_items_as_items(session): with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add(responses.POST, f'{PROTOCOL}//archive.org/services/search/v1/scrape', body=TEST_SCRAPE_RESPONSE) rsps.add_metadata_mock('nasa') r = search_items('identifier:nasa', archive_session=session) assert [x.identifier for x in r.iter_as_items()] == ['nasa'] assert r.iter_as_items().search == r def test_search_items_fts(session): with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add(responses.POST, f'{PROTOCOL}//be-api.us.archive.org/ia-pub-fts-api', body=TEST_SCRAPE_RESPONSE) rsps.add_metadata_mock('nasa') r = search_items('nina simone', full_text_search=True, archive_session=session) print(r.search_url) assert r.fts == True assert r.dsl_fts == False assert r.query == '!L nina simone' assert r.params == {'count': 10000, 'q': '!L nina simone'} r = search_items('nina simone', full_text_search=True, dsl_fts=True, archive_session=session) assert r.fts == True assert r.dsl_fts == True assert r.query == 'nina simone' assert r.params == {'count': 10000, 'q': 'nina simone'} r = search_items('nina simone', dsl_fts=True, archive_session=session) assert r.fts == True assert r.dsl_fts == True assert r.query == 'nina simone' assert r.params == {'count': 10000, 'q': 'nina simone'} def test_page_row_specification(session): _j = json.loads(TEST_SEARCH_RESPONSE) _j['response']['items'] = [{'identifier': 'nasa'}] _j['response']['numFound'] = 1 _search_r = json.dumps(_j) with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add(responses.GET, f'{PROTOCOL}//archive.org/advancedsearch.php', body=_search_r) rsps.add_metadata_mock('nasa') rsps.add(responses.POST, f'{PROTOCOL}//archive.org/services/search/v1/scrape', body='{"items":[],"count":0,"total":1}', content_type='application/json; charset=UTF-8') r = search_items('identifier:nasa', params={'page': '1', 'rows': '1'}, archive_session=session) assert r.iter_as_items().search == r assert len(r.iter_as_items()) == 1
14,514
Python
.py
341
33.079179
85
0.588323
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,436
test_utils.py
jjjake_internetarchive/tests/test_utils.py
import string import internetarchive.utils from tests.conftest import NASA_METADATA_PATH, IaRequestsMock def test_utils(): with open(__file__, encoding='utf-8') as fh: list(internetarchive.utils.chunk_generator(fh, 10)) ifp = internetarchive.utils.IterableToFileAdapter([1, 2], 200) assert len(ifp) == 200 ifp.read() def test_needs_quote(): notascii = ('ȧƈƈḗƞŧḗḓ ŧḗẋŧ ƒǿř ŧḗşŧīƞɠ, ℛℯα∂α♭ℓℯ ♭ʊ☂ η☺т Ѧ$☾ℐℐ, ' '¡ooʇ ןnɟǝsn sı uʍop-ǝpısdn') assert internetarchive.utils.needs_quote(notascii) assert internetarchive.utils.needs_quote(string.whitespace) assert not internetarchive.utils.needs_quote(string.ascii_letters + string.digits) def test_validate_s3_identifier(): id1 = 'valid-Id-123-_foo' id2 = '!invalid-Id-123-_foo' id3 = 'invalid-Id-123-_foo+bar' id4 = 'invalid-Id-123-_føø' id5 = 'i' valid = internetarchive.utils.validate_s3_identifier(id1) assert valid for invalid_id in [id2, id3, id4, id5]: try: internetarchive.utils.validate_s3_identifier(invalid_id) except Exception as exc: assert isinstance(exc, internetarchive.utils.InvalidIdentifierException) def test_get_md5(): with open(__file__, 'rb') as fp: md5 = internetarchive.utils.get_md5(fp) assert isinstance(md5, str) def test_IdentifierListAsItems(session): with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add_metadata_mock('nasa') it = internetarchive.utils.IdentifierListAsItems('nasa', session) assert it[0].identifier == 'nasa' assert it.nasa.identifier == 'nasa' def test_IdentifierListAsItems_len(session): assert len(internetarchive.utils.IdentifierListAsItems(['foo', 'bar'], session)) == 2 # TODO: Add test of slice access to IdenfierListAsItems def test_get_s3_xml_text(): xml_str = ('<Error><Code>NoSuchBucket</Code>' '<Message>The specified bucket does not exist.</Message>' '<Resource>' 'does-not-exist-! not found by Metadata::get_obj()[server]' '</Resource>' '<RequestId>d56bdc63-169b-4b4f-8c47-0fac6de39040</RequestId></Error>') expected_txt = internetarchive.utils.get_s3_xml_text(xml_str) assert expected_txt == ('The specified bucket does not exist. - does-not-exist-! ' 'not found by Metadata::get_obj()[server]') def test_get_file_size(): try: s = internetarchive.utils.get_file_size(NASA_METADATA_PATH) except AttributeError as exc: assert "object has no attribute 'seek'" in str(exc) with open(NASA_METADATA_PATH) as fp: s = internetarchive.utils.get_file_size(fp) assert s == 7557 def test_is_valid_metadata_key(): # Keys starting with "xml" should also be invalid # due to the XML specification, but are supported # by the Internet Archive. valid = ('adaptive_ocr', 'bookreader-defaults', 'frames_per_second', 'identifier', 'possible-copyright-status', 'index[0]') invalid = ('Analog Format', "Date of transfer (probably today's date)", '_metadata_key', '58', '_', '<invalid>', 'a') for metadata_key in valid: assert internetarchive.utils.is_valid_metadata_key(metadata_key) for metadata_key in invalid: assert not internetarchive.utils.is_valid_metadata_key(metadata_key)
3,493
Python
.py
71
41.070423
89
0.676285
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,437
test_item.py
jjjake_internetarchive/tests/test_item.py
import logging import os import re import types from copy import deepcopy import pytest import responses from requests.exceptions import ConnectionError, HTTPError import internetarchive.files from internetarchive import get_session from internetarchive.api import get_item from internetarchive.exceptions import InvalidChecksumError from internetarchive.utils import InvalidIdentifierException, json, norm_filepath from tests.conftest import ( NASA_METADATA_PATH, PROTOCOL, IaRequestsMock, load_file, load_test_data_file, ) S3_URL = f'{PROTOCOL}//s3.us.archive.org/' DOWNLOAD_URL_RE = re.compile(f'{PROTOCOL}//archive.org/download/.*') S3_URL_RE = re.compile(r'.*s3.us.archive.org/.*') EXPECTED_LAST_MOD_HEADER = {"Last-Modified": "Tue, 14 Nov 2023 20:25:48 GMT"} EXPECTED_S3_HEADERS = { 'content-length': '7557', 'x-archive-queue-derive': '1', 'x-archive-meta00-scanner': 'uri(Internet%20Archive%20Python%20library', 'x-archive-size-hint': '7557', 'x-archive-auto-make-bucket': '1', 'authorization': 'LOW a:b', 'accept': '*/*', 'accept-encoding': 'gzip, deflate', 'connection': 'close', } def test_get_item(nasa_metadata, nasa_item, session): assert nasa_item.item_metadata == nasa_metadata assert nasa_item.identifier == 'nasa' assert nasa_item.exists is True assert isinstance(nasa_item.metadata, dict) assert isinstance(nasa_item.files, list) assert isinstance(nasa_item.reviews, list) assert nasa_item.created == 1427273784 assert nasa_item.d1 == 'ia902606.us.archive.org' assert nasa_item.d2 == 'ia802606.us.archive.org' assert nasa_item.dir == '/7/items/nasa' assert nasa_item.files_count == 6 assert nasa_item.item_size == 114030 assert nasa_item.server == 'ia902606.us.archive.org' assert nasa_item.uniq == 2131998567 assert nasa_item.updated == 1427273788 assert nasa_item.tasks is None assert len(nasa_item.collection) == 1 def test_get_file(nasa_item): file = nasa_item.get_file('nasa_meta.xml') assert type(file) == internetarchive.files.File assert file.name == 'nasa_meta.xml' def test_get_files(nasa_item): files = nasa_item.get_files() assert isinstance(files, types.GeneratorType) expected_files = {'NASAarchiveLogo.jpg', 'globe_west_540.jpg', 'nasa_reviews.xml', 'nasa_meta.xml', 'nasa_archive.torrent', 'nasa_files.xml'} files = {x.name for x in files} assert files == expected_files def test_get_files_by_name(nasa_item): files = nasa_item.get_files('globe_west_540.jpg') assert {f.name for f in files} == {'globe_west_540.jpg'} files = nasa_item.get_files(['globe_west_540.jpg', 'nasa_meta.xml']) assert {f.name for f in files} == {'globe_west_540.jpg', 'nasa_meta.xml'} def test_get_files_by_formats(nasa_item): files = {f.name for f in nasa_item.get_files(formats='Archive BitTorrent')} expected_files = {'nasa_archive.torrent'} assert files == expected_files files = {f.name for f in nasa_item.get_files(formats=['Archive BitTorrent', 'JPEG'])} expected_files = {'nasa_archive.torrent', 'globe_west_540.jpg'} assert files == expected_files def test_get_files_by_glob(nasa_item): files = {f.name for f in nasa_item.get_files(glob_pattern='*jpg|*torrent')} expected_files = {'NASAarchiveLogo.jpg', 'globe_west_540.jpg', 'nasa_archive.torrent'} assert files == expected_files files = {f.name for f in nasa_item.get_files(glob_pattern=['*jpg', '*torrent'])} expected_files = {'NASAarchiveLogo.jpg', 'globe_west_540.jpg', 'nasa_archive.torrent'} assert files == expected_files def test_get_files_by_glob_with_exclude(nasa_item): files = { f.name for f in nasa_item.get_files( glob_pattern="*jpg|*torrent", exclude_pattern="*540*|*Logo*" ) } expected_files = {"nasa_archive.torrent"} assert files == expected_files files = { f.name for f in nasa_item.get_files( glob_pattern=["*jpg", "*torrent"], exclude_pattern=["*540*", "*Logo*"] ) } expected_files = {"nasa_archive.torrent"} assert files == expected_files def test_get_files_with_multiple_filters(nasa_item): files = {f.name for f in nasa_item.get_files(formats='JPEG', glob_pattern='*xml')} expected_files = {'globe_west_540.jpg', 'nasa_reviews.xml', 'nasa_meta.xml', 'nasa_files.xml'} assert files == expected_files def test_get_files_no_matches(nasa_item): assert list(nasa_item.get_files(formats='none')) == [] def test_download(tmpdir, nasa_item): tmpdir.chdir() with IaRequestsMock() as rsps: rsps.add(responses.GET, DOWNLOAD_URL_RE, body='test content', adding_headers=EXPECTED_LAST_MOD_HEADER) nasa_item.download(files='nasa_meta.xml') assert len(tmpdir.listdir()) == 1 os.remove('nasa/nasa_meta.xml') with IaRequestsMock() as rsps: rsps.add(responses.GET, DOWNLOAD_URL_RE, body='new test content', adding_headers=EXPECTED_LAST_MOD_HEADER) nasa_item.download(files='nasa_meta.xml') with open('nasa/nasa_meta.xml') as fh: assert fh.read() == 'new test content' def test_download_io_error(tmpdir, nasa_item): tmpdir.chdir() with IaRequestsMock() as rsps: rsps.add(responses.GET, DOWNLOAD_URL_RE, body='test content', adding_headers=EXPECTED_LAST_MOD_HEADER) nasa_item.download(files='nasa_meta.xml') rsps.reset() with pytest.raises(ConnectionError): nasa_item.download(files='nasa_meta.xml') def test_download_ignore_errors(tmpdir, nasa_item): with IaRequestsMock() as rsps: rsps.add(responses.GET, DOWNLOAD_URL_RE, body='test content', adding_headers=EXPECTED_LAST_MOD_HEADER) nasa_item.download(files='nasa_meta.xml') nasa_item.download(files='nasa_meta.xml', ignore_errors=True) def test_download_ignore_existing(tmpdir, nasa_item): tmpdir.chdir() with IaRequestsMock( assert_all_requests_are_fired=False) as rsps: rsps.add(responses.GET, DOWNLOAD_URL_RE, body='test content', adding_headers=EXPECTED_LAST_MOD_HEADER) nasa_item.download(files='nasa_meta.xml', ignore_existing=True) rsps.add(responses.GET, DOWNLOAD_URL_RE, body='new test content', adding_headers=EXPECTED_LAST_MOD_HEADER) nasa_item.download(files='nasa_meta.xml', ignore_existing=True) with open('nasa/nasa_meta.xml') as fh: assert fh.read() == 'test content' def test_download_checksum(tmpdir, caplog): tmpdir.chdir() # test overwrite based on checksum. if os.path.exists('nasa/nasa_meta.xml'): os.remove('nasa/nasa_meta.xml') with IaRequestsMock() as rsps: rsps.add_metadata_mock('nasa') rsps.add(responses.GET, DOWNLOAD_URL_RE, body='test content', adding_headers=EXPECTED_LAST_MOD_HEADER) rsps.add(responses.GET, DOWNLOAD_URL_RE, body='overwrite based on md5', adding_headers=EXPECTED_LAST_MOD_HEADER) nasa_item = get_item('nasa') nasa_item.download(files='nasa_meta.xml') try: nasa_item.download(files='nasa_meta.xml', checksum=True) except InvalidChecksumError as exc: assert "corrupt, checksums do not match." in str(exc) # test no overwrite based on checksum. with caplog.at_level(logging.DEBUG): rsps.reset() rsps.add(responses.GET, DOWNLOAD_URL_RE, body=load_test_data_file('nasa_meta.xml'), adding_headers=EXPECTED_LAST_MOD_HEADER) nasa_item.download(files='nasa_meta.xml', checksum=True, verbose=True) nasa_item.download(files='nasa_meta.xml', checksum=True, verbose=True) assert 'skipping nasa' in caplog.text assert 'nasa_meta.xml, file already exists based on checksum.' in caplog.text def test_download_destdir(tmpdir, nasa_item): tmpdir.chdir() with IaRequestsMock() as rsps: rsps.add(responses.GET, DOWNLOAD_URL_RE, body='new destdir', adding_headers=EXPECTED_LAST_MOD_HEADER) dest = os.path.join(str(tmpdir), 'new destdir') nasa_item.download(files='nasa_meta.xml', destdir=dest) assert 'nasa' in os.listdir(dest) with open(os.path.join(dest, 'nasa/nasa_meta.xml')) as fh: assert fh.read() == 'new destdir' def test_download_no_directory(tmpdir, nasa_item): url_re = re.compile(f'{PROTOCOL}//archive.org/download/.*') tmpdir.chdir() with IaRequestsMock() as rsps: rsps.add(responses.GET, url_re, body='no dest dir', adding_headers=EXPECTED_LAST_MOD_HEADER) nasa_item.download(files='nasa_meta.xml', no_directory=True) with open(os.path.join(str(tmpdir), 'nasa_meta.xml')) as fh: assert fh.read() == 'no dest dir' def test_download_dry_run(tmpdir, capsys, nasa_item): tmpdir.chdir() with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add(responses.GET, DOWNLOAD_URL_RE, body='no dest dir', adding_headers={'content-length': '100'}) nasa_item.download(formats='Metadata', dry_run=True) expected = {'nasa_reviews.xml', 'nasa_meta.xml', 'nasa_files.xml'} out, err = capsys.readouterr() assert {x.split('/')[-1] for x in out.split('\n') if x} == expected def test_download_dry_run_on_the_fly_formats(tmpdir, capsys, nasa_item): tmpdir.chdir() with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add(responses.GET, DOWNLOAD_URL_RE, body='no dest dir', adding_headers={'content-length': '100'}) nasa_item.download(formats='MARCXML', on_the_fly=True, dry_run=True) expected = {'nasa_archive_marc.xml'} out, err = capsys.readouterr() assert {x.split('/')[-1] for x in out.split('\n') if x} == expected def test_download_verbose(tmpdir, capsys, nasa_item): tmpdir.chdir() with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: headers = {'content-length': '11'} headers.update(EXPECTED_LAST_MOD_HEADER) rsps.add(responses.GET, DOWNLOAD_URL_RE, body='no dest dir', adding_headers=headers) nasa_item.download(files='nasa_meta.xml', verbose=True) out, err = capsys.readouterr() assert 'downloading nasa_meta.xml' in err def test_download_dark_item(tmpdir, capsys, nasa_metadata, session): tmpdir.chdir() with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: nasa_metadata['metadata']['identifier'] = 'dark-item' nasa_metadata['is_dark'] = True _item_metadata = json.dumps(nasa_metadata) rsps.add(responses.GET, f'{PROTOCOL}//archive.org/metadata/dark-item', body=_item_metadata, content_type='application/json') _item = session.get_item('dark-item') rsps.add(responses.GET, DOWNLOAD_URL_RE, body='no dest dir', status=403, adding_headers={'content-length': '100'}) _item.download(files='nasa_meta.xml', verbose=True) out, err = capsys.readouterr() assert 'skipping dark-item, item is dark' in err def test_upload(nasa_item): with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add(responses.PUT, S3_URL_RE, adding_headers=EXPECTED_S3_HEADERS) _responses = nasa_item.upload(NASA_METADATA_PATH, access_key='a', secret_key='b') for resp in _responses: request = resp.request headers = {k.lower(): str(v) for k, v in request.headers.items()} scanner_header = '%20'.join( resp.headers['x-archive-meta00-scanner'].split('%20')[:4]) headers['x-archive-meta00-scanner'] = scanner_header assert 'user-agent' in headers del headers['user-agent'] assert headers == EXPECTED_S3_HEADERS assert request.url == f'{PROTOCOL}//s3.us.archive.org/nasa/nasa.json' def test_upload_validate_identifier(session): item = session.get_item('føø') with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add(responses.PUT, S3_URL_RE, adding_headers=EXPECTED_S3_HEADERS) try: item.upload(NASA_METADATA_PATH, access_key='a', secret_key='b', validate_identifier=True) raise AssertionError("Given invalid identifier was not correctly validated.") except Exception as exc: assert isinstance(exc, InvalidIdentifierException) valid_item = session.get_item('foo') with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add(responses.PUT, S3_URL_RE, adding_headers=EXPECTED_S3_HEADERS) valid_item.upload(NASA_METADATA_PATH, access_key='a', secret_key='b', validate_identifier=True) assert True def test_upload_secure_session(): with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: c = {'s3': {'access': 'foo', 'secret': 'bar'}, 'general': {'secure': True}} s = get_session(config=c) rsps.add_metadata_mock('nasa') item = s.get_item('nasa') with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add(responses.PUT, S3_URL_RE) r = item.upload(NASA_METADATA_PATH) assert r[0].url == 'https://s3.us.archive.org/nasa/nasa.json' def test_upload_metadata(nasa_item): with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: _expected_headers = deepcopy(EXPECTED_S3_HEADERS) del _expected_headers['x-archive-meta00-scanner'] _expected_headers['x-archive-meta00-foo'] = 'bar' _expected_headers['x-archive-meta00-subject'] = 'first' _expected_headers['x-archive-meta01-subject'] = 'second' _expected_headers['x-archive-meta00-baz'] = ( 'uri(%D0%9F%D0%BE%D1%87%D0%B5%D0%BC' '%D1%83%20%D0%B1%D1%8B%20%D0%B8%20%' 'D0%BD%D0%B5%D1%82...)') _expected_headers['x-archive-meta00-baz2'] = ( 'uri(%D0%9F%D0%BE%D1%87%D0%B5%D0%BC' '%D1%83%20%D0%B1%D1%8B%20%D0%B8%20%' 'D0%BD%D0%B5%D1%82...)') rsps.add(responses.PUT, S3_URL_RE, adding_headers=_expected_headers) md = { 'foo': 'bar', 'subject': ['first', 'second'], 'baz': 'Почему бы и нет...', 'baz2': ('\u041f\u043e\u0447\u0435\u043c\u0443 \u0431\u044b \u0438 ' '\u043d\u0435\u0442...'), } _responses = nasa_item.upload(NASA_METADATA_PATH, metadata=md, access_key='a', secret_key='b') for resp in _responses: request = resp.request del request.headers['x-archive-meta00-scanner'] headers = {k.lower(): str(v) for k, v in request.headers.items()} assert 'user-agent' in headers del headers['user-agent'] assert headers == _expected_headers def test_upload_503(capsys, nasa_item): body = ("<?xml version='1.0' encoding='UTF-8'?>" '<Error><Code>SlowDown</Code><Message>Please reduce your request rate.' '</Message><Resource>simulated error caused by x-(amz|archive)-simulate-error' ', try x-archive-simulate-error:help</Resource><RequestId>d36ec445-8d4a-4a64-' 'a110-f67af6ee2c2a</RequestId></Error>') with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: _expected_headers = deepcopy(EXPECTED_S3_HEADERS) rsps.add(responses.GET, S3_URL_RE, body='{"over_limit": "1"}', adding_headers={'content-length': '19'} ) _expected_headers['content-length'] = '296' rsps.add(responses.PUT, S3_URL_RE, body=body, adding_headers=_expected_headers, status=503) try: nasa_item.upload(NASA_METADATA_PATH, access_key='a', secret_key='b', retries=1, retries_sleep=.1, verbose=True) except Exception as exc: assert 'Please reduce your request rate' in str(exc) out, err = capsys.readouterr() assert 'warning: s3 is overloaded' in err def test_upload_file_keys(nasa_item): with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add(responses.PUT, S3_URL_RE, adding_headers=EXPECTED_S3_HEADERS) files = {'new_key.txt': NASA_METADATA_PATH, '222': NASA_METADATA_PATH} _responses = nasa_item.upload(files, access_key='a', secret_key='b') expected_urls = [ f'{PROTOCOL}//s3.us.archive.org/nasa/new_key.txt', f'{PROTOCOL}//s3.us.archive.org/nasa/222', ] for resp in _responses: assert resp.request.url in expected_urls def test_upload_dir(tmpdir, nasa_item): with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add(responses.PUT, S3_URL_RE, adding_headers=EXPECTED_S3_HEADERS) tmpdir.mkdir('dir_test') with open(os.path.join(str(tmpdir), 'dir_test', 'foo.txt'), 'w') as fh: fh.write('hi') with open(os.path.join(str(tmpdir), 'dir_test', 'foo2.txt'), 'w') as fh: fh.write('hi 2') # Test no-slash upload, dir is not in key name. _responses = nasa_item.upload(os.path.join(str(tmpdir), 'dir_test') + '/', access_key='a', secret_key='b') expected_eps = [ f'{S3_URL}nasa/foo.txt', f'{S3_URL}nasa/foo2.txt', ] for resp in _responses: assert resp.request.url in expected_eps # Test slash upload, dir is in key name. _responses = nasa_item.upload(os.path.join(str(tmpdir), 'dir_test'), access_key='a', secret_key='b') tmp_path = norm_filepath(str(tmpdir)) expected_eps = [ f'{S3_URL}nasa{tmp_path}/dir_test/foo.txt', f'{S3_URL}nasa{tmp_path}/dir_test/foo2.txt', ] for resp in _responses: assert resp.request.url in expected_eps def test_upload_queue_derive(nasa_item): with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: _expected_headers = deepcopy(EXPECTED_S3_HEADERS) _expected_headers['x-archive-queue-derive'] = '1' del _expected_headers['x-archive-meta00-scanner'] rsps.add(responses.PUT, S3_URL_RE, adding_headers=_expected_headers) _responses = nasa_item.upload(NASA_METADATA_PATH, access_key='a', secret_key='b') for resp in _responses: headers = {k.lower(): str(v) for k, v in resp.request.headers.items()} del headers['x-archive-meta00-scanner'] assert 'user-agent' in headers del headers['user-agent'] assert headers == _expected_headers def test_upload_delete(tmpdir, nasa_item): body = ("<?xml version='1.0' encoding='UTF-8'?>" '<Error><Code>BadDigest</Code><Message>The Content-MD5 you specified did not ' 'match what we received.</Message><Resource>content-md5 submitted with PUT: ' 'foo != received data md5: 70871f9fce8dd23853d6e42417356b05also not equal to ' 'base64 version: cIcfn86N0jhT1uQkFzVrBQ==</Resource><RequestId>ec03fe7c-e123-' '4133-a207-3141d4d74096</RequestId></Error>') _expected_headers = deepcopy(EXPECTED_S3_HEADERS) _expected_headers['content-length'] = '383' del _expected_headers['x-archive-meta00-scanner'] tmpdir.chdir() test_file = os.path.join(str(tmpdir), 'test.txt') with open(test_file, 'w') as fh: fh.write('test delete') with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: # Non-matching md5, should not delete. rsps.add(responses.PUT, S3_URL_RE, body=body, adding_headers=_expected_headers, status=400) with pytest.raises(HTTPError): nasa_item.upload(test_file, access_key='a', secret_key='b', delete=True, queue_derive=True) assert len(tmpdir.listdir()) == 1 _expected_headers = deepcopy(EXPECTED_S3_HEADERS) test_file = os.path.join(str(tmpdir), 'test.txt') with open(test_file, 'w') as fh: fh.write('test delete') # Matching md5, should delete. with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add(responses.PUT, S3_URL_RE, adding_headers=_expected_headers) resp = nasa_item.upload(test_file, access_key='a', secret_key='b', delete=True, queue_derive=True) for r in resp: headers = {k.lower(): str(v) for k, v in r.headers.items()} del headers['content-type'] assert headers == _expected_headers assert len(tmpdir.listdir()) == 0 def test_upload_checksum(tmpdir, nasa_item): with IaRequestsMock() as rsps: rsps.add_metadata_mock('nasa') nasa_item = get_item('nasa') _expected_headers = deepcopy(EXPECTED_S3_HEADERS) del _expected_headers['x-archive-meta00-scanner'] _expected_headers['content-md5'] = '6f1834f5c70c0eabf93dea675ccf90c4' test_file = os.path.join(str(tmpdir), 'checksum_test.txt') with open(test_file, 'wb') as fh: fh.write(b'test delete') # No skip. rsps.add(responses.PUT, S3_URL_RE, adding_headers=_expected_headers) resp = nasa_item.upload(test_file, access_key='a', secret_key='b', checksum=True) for r in resp: headers = {k.lower(): str(v) for k, v in r.headers.items()} del headers['content-type'] assert headers == _expected_headers assert r.status_code == 200 # Skip. nasa_item.item_metadata['files'].append( {'name': 'checksum_test.txt', 'md5': '33213e7683c1e6d15b2a658f3c567717'}) resp = nasa_item.upload(test_file, access_key='a', secret_key='b', checksum=True) for r in resp: headers = {k.lower(): str(v) for k, v in r.headers.items()} assert r.status_code is None def test_upload_automatic_size_hint(tmpdir, nasa_item): with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: _expected_headers = deepcopy(EXPECTED_S3_HEADERS) del _expected_headers['x-archive-size-hint'] _expected_headers['x-archive-size-hint'] = '15' rsps.add(responses.PUT, S3_URL_RE, adding_headers=_expected_headers) files = [] with open(os.path.join(tmpdir, 'file'), 'w') as fh: fh.write('a') files.append(os.path.join(tmpdir, 'file')) os.mkdir(os.path.join(tmpdir, 'dir')) with open(os.path.join(tmpdir, 'dir', 'file0'), 'w') as fh: fh.write('bb') with open(os.path.join(tmpdir, 'dir', 'file1'), 'w') as fh: fh.write('cccc') files.append(os.path.join(tmpdir, 'dir')) with open(os.path.join(tmpdir, 'obj'), 'wb') as fh: fh.write(b'dddddddd') fh.seek(0, os.SEEK_SET) files.append(fh) _responses = nasa_item.upload(files, access_key='a', secret_key='b') for r in _responses: headers = {k.lower(): str(v) for k, v in r.headers.items()} del headers['content-type'] assert headers == _expected_headers def test_modify_metadata(nasa_item, nasa_metadata): with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add(responses.POST, f'{PROTOCOL}//archive.org/metadata/nasa') # Test simple add. md = {'foo': 'bar'} p = nasa_item.modify_metadata(md, debug=True) _patch = json.dumps([ {'add': '/foo', 'value': 'bar'}, ]) expected_data = { 'priority': -5, '-target': 'metadata', '-patch': _patch, } assert set(p.data.keys()) == set(expected_data.keys()) assert p.data['priority'] == expected_data['priority'] assert p.data['-target'] == expected_data['-target'] assert all(v in p.data['-patch'] for v in ['/foo', 'bar']) # Test no changes. md = {'title': 'NASA Images'} p = nasa_item.modify_metadata(md, debug=True) expected_data = {'priority': -5, '-target': 'metadata', '-patch': '[]'} assert p.data == expected_data md = {'title': 'REMOVE_TAG'} p = nasa_item.modify_metadata(md, debug=True) expected_data = { 'priority': -5, '-target': 'metadata', '-patch': json.dumps([{'remove': '/title'}]) } assert set(p.data.keys()) == set(expected_data.keys()) assert p.data['priority'] == expected_data['priority'] assert p.data['-target'] == expected_data['-target'] assert '/title' in str(p.data['-patch']) assert 'remove' in str(p.data['-patch']) # Test add array. md = {'subject': ['one', 'two', 'last']} p = nasa_item.modify_metadata(md, debug=True, priority=-1) expected_data = { 'priority': -1, '-target': 'metadata', '-patch': json.dumps([{'add': '/subject', 'value': ['one', 'two', 'last']}]) } assert set(p.data.keys()) == set(expected_data.keys()) assert p.data['priority'] == expected_data['priority'] assert p.data['-target'] == expected_data['-target'] assert '["one", "two", "last"]' in str(p.data['-patch']) \ or '["one","two","last"]' in str(p.data['-patch']) # Test indexed mod. nasa_item.item_metadata['metadata']['subject'] = ['first', 'middle', 'last'] md = {'subject[2]': 'new first'} p = nasa_item.modify_metadata(md, debug=True) expected_data = { 'priority': -5, '-target': 'metadata', '-patch': json.dumps([{'value': 'new first', 'replace': '/subject/2'}]) } # Avoid comparing the json strings, because they are not in a canonical form assert set(p.data.keys()) == set(expected_data.keys()) assert all(p.data[k] == expected_data[k] for k in ['priority', '-target']) assert '/subject/2' in p.data['-patch'] or r'\/subject\/2' in p.data['-patch'] # Test priority. md = {'title': 'NASA Images'} p = nasa_item.modify_metadata(md, priority=3, debug=True) expected_data = {'priority': 3, '-target': 'metadata', '-patch': '[]'} assert p.data == expected_data # Test auth. md = {'title': 'NASA Images'} p = nasa_item.modify_metadata(md, access_key='a', secret_key='b', debug=True) assert 'access=a' in p.body assert 'secret=b' in p.body # Test change. md = {'title': 'new title'} nasa_metadata['metadata']['title'] = 'new title' _item_metadata = json.dumps(nasa_metadata) rsps.add(responses.GET, f'{PROTOCOL}//archive.org/metadata/nasa', body=_item_metadata) nasa_item.modify_metadata(md, access_key='a', secret_key='b') # Test that item re-initializes assert nasa_item.metadata['title'] == 'new title'
29,248
Python
.py
616
36.397727
94
0.586686
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,438
test_exceptions.py
jjjake_internetarchive/tests/test_exceptions.py
import internetarchive.exceptions def test_AuthenticationError(): try: raise internetarchive.exceptions.AuthenticationError('Authentication Failed') except Exception as exc: assert str(exc) == 'Authentication Failed'
243
Python
.py
6
35.166667
85
0.770213
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,439
test_session.py
jjjake_internetarchive/tests/test_session.py
import os import responses import internetarchive.session from internetarchive import __version__ from tests.conftest import NASA_METADATA_PATH, PROTOCOL, IaRequestsMock CONFIG = { 's3': { 'access': 'test_access', 'secret': 'test_secret', }, 'cookies': { 'logged-in-user': 'test%40example.com; path=/; domain=.archive.org', 'logged-in-sig': 'testsig; path=/; domain=.archive.org', }, 'logging': { 'level': 'INFO', 'file': 'test.log', }, } def test_archive_session(tmpdir): tmpdir.chdir() s = internetarchive.session.ArchiveSession(CONFIG) assert os.path.isfile('test.log') assert CONFIG == s.config assert set(s.cookies.keys()) == set(CONFIG['cookies'].keys()) assert s.secure is True assert s.protocol == PROTOCOL assert s.access_key == 'test_access' assert s.secret_key == 'test_secret' assert s.headers['user-agent'].startswith(f'internetarchive/{__version__}') def test_get_item(tmpdir): tmpdir.chdir() with open(NASA_METADATA_PATH) as fh: item_metadata = fh.read().strip() with responses.RequestsMock() as rsps: rsps.add(responses.GET, f'{PROTOCOL}//archive.org/metadata/nasa', body=item_metadata, content_type='application/json') s = internetarchive.session.ArchiveSession() item = s.get_item('nasa') assert item.exists is True assert item.identifier == 'nasa' with responses.RequestsMock() as rsps: rsps.add(responses.GET, f'{PROTOCOL}//archive.org/metadata/nasa', body=item_metadata, status=400, content_type='application/json') s = internetarchive.session.ArchiveSession(CONFIG) try: item = s.get_item('nasa') except Exception: with open('test.log') as fh: assert '400 Client Error' in fh.read() def test_s3_is_overloaded(): test_body = """{ "accesskey": "test_access", "bucket": "nasa", "detail": { "accesskey_ration": 74, "accesskey_tasks_queued": 0, "bucket_ration": 24, "bucket_tasks_queued": 0, "limit_reason": "", "rationing_engaged": 0, "rationing_level": 1399, "total_global_limit": 1799, "total_tasks_queued": 308 }, "over_limit": 0 }""" with IaRequestsMock() as rsps: rsps.add(responses.GET, f'{PROTOCOL}//s3.us.archive.org', body=test_body, content_type='application/json') s = internetarchive.session.ArchiveSession(CONFIG) r = s.s3_is_overloaded('nasa') assert r is False test_body = """{ "accesskey": "test_access", "bucket": "nasa", "detail": { "accesskey_ration": 74, "accesskey_tasks_queued": 0, "bucket_ration": 24, "bucket_tasks_queued": 0, "limit_reason": "", "rationing_engaged": 0, "rationing_level": 1399, "total_global_limit": 1799, "total_tasks_queued": 308 }, "over_limit": 1 }""" with responses.RequestsMock() as rsps: rsps.add(responses.GET, f'{PROTOCOL}//s3.us.archive.org', body=test_body, content_type='application/json') s = internetarchive.session.ArchiveSession(CONFIG) r = s.s3_is_overloaded('nasa') assert r is True def test_cookies(): with responses.RequestsMock() as rsps: rsps.add(responses.GET, f'{PROTOCOL}//archive.org') s = internetarchive.session.ArchiveSession(CONFIG) r = s.get(f'{PROTOCOL}//archive.org') assert 'logged-in-sig' in r.request.headers['Cookie'] assert 'logged-in-user' in r.request.headers['Cookie'] for c in s.cookies: if c.name.startswith('logged-in-'): assert c.domain == '.archive.org' with responses.RequestsMock() as rsps: rsps.add(responses.GET, f'{PROTOCOL}//example.com') s = internetarchive.session.ArchiveSession(CONFIG) r = s.get(f'{PROTOCOL}//example.com') assert 'logged-in-sig' not in r.request.headers.get('Cookie', '') assert 'logged-in-user' not in r.request.headers.get('Cookie', '') assert '.archive.org' not in r.request.headers.get('Cookie', '')
4,477
Python
.py
117
29.239316
79
0.58829
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,440
test_config.py
jjjake_internetarchive/tests/test_config.py
import contextlib import os import tempfile from unittest import mock import pytest import requests.adapters import responses import internetarchive.config import internetarchive.session from internetarchive.exceptions import AuthenticationError @responses.activate def test_get_auth_config(): test_body = """{ "success": true, "values": { "cookies": { "logged-in-sig": "foo-sig", "logged-in-user": "foo%40example.com" }, "email": "foo@example.com", "itemname": "@jakej", "s3": { "access": "Ac3ssK3y", "secret": "S3cretK3y" }, "screenname":"jakej" }, "version": 1}""" responses.add(responses.POST, 'https://archive.org/services/xauthn/', body=test_body) r = internetarchive.config.get_auth_config('test@example.com', 'password1') assert r['s3']['access'] == 'Ac3ssK3y' assert r['s3']['secret'] == 'S3cretK3y' assert r['cookies']['logged-in-user'] == 'foo%40example.com' assert r['cookies']['logged-in-sig'] == 'foo-sig' @responses.activate def test_get_auth_config_auth_fail(): # No logged-in-sig cookie set raises AuthenticationError. responses.add(responses.POST, 'https://archive.org/services/xauthn/', body='{"error": "failed"}') try: r = internetarchive.config.get_auth_config('test@example.com', 'password1') except AuthenticationError as exc: return assert str(exc) == ('Authentication failed. Please check your credentials ' 'and try again.') def test_get_config(): config = internetarchive.config.get_config() assert isinstance(config, dict) def test_get_config_with_config_file(tmpdir): test_conf = ('[s3]\n' 'access = test-access\n' 'secret = test-secret\n' '[cookies]\n' 'logged-in-sig = test-sig\n' 'logged-in-user = test@archive.org\n') tmpdir.chdir() with open('ia_test.ini', 'w') as fp: fp.write(test_conf) config = internetarchive.config.get_config(config_file='ia_test.ini', config={'custom': 'test'}) assert config['cookies']['logged-in-sig'] == 'test-sig' assert config['cookies']['logged-in-user'] == 'test@archive.org' assert config['s3']['access'] == 'test-access' assert config['s3']['secret'] == 'test-secret' assert config['custom'] == 'test' def test_get_config_no_config_file(): os.environ['HOME'] = '' config = internetarchive.config.get_config() assert config == {} def test_get_config_with_config(): test_conf = { 's3': { 'access': 'custom-access', 'secret': 'custom-secret', }, 'cookies': { 'logged-in-user': 'test@archive.org', 'logged-in-sig': 'test-sig', }, } os.environ['HOME'] = '' config = internetarchive.config.get_config(config=test_conf) assert config['cookies']['logged-in-sig'] == 'test-sig' assert config['cookies']['logged-in-user'] == 'test@archive.org' assert config['s3']['access'] == 'custom-access' assert config['s3']['secret'] == 'custom-secret' def test_get_config_home_not_set(): os.environ['HOME'] = '/none' config = internetarchive.config.get_config() assert isinstance(config, dict) def test_get_config_home_not_set_with_config(): test_conf = { 's3': { 'access': 'no-home-access', 'secret': 'no-home-secret', }, } os.environ['HOME'] = '/none' config = internetarchive.config.get_config(config=test_conf) assert isinstance(config, dict) assert config['s3']['access'] == 'no-home-access' assert config['s3']['secret'] == 'no-home-secret' def test_get_config_config_and_config_file(tmpdir): test_conf = ('[s3]\n' 'access = test-access\n' 'secret = test-secret\n' '[cookies]\n' 'logged-in-sig = test-sig\n' 'logged-in-user = test@archive.org\n') tmpdir.chdir() with open('ia_test.ini', 'w') as fp: fp.write(test_conf) test_conf = { 's3': { 'access': 'custom-access', 'secret': 'custom-secret', }, 'cookies': { 'logged-in-user': 'test@archive.org', 'logged-in-sig': 'test-sig', }, } del test_conf['s3']['access'] config = internetarchive.config.get_config(config_file='ia_test.ini', config=test_conf) assert config['cookies']['logged-in-sig'] == 'test-sig' assert config['cookies']['logged-in-user'] == 'test@archive.org' assert config['s3']['access'] == 'test-access' assert config['s3']['secret'] == 'custom-secret' @contextlib.contextmanager def _environ(**kwargs): old_values = {k: os.environ.get(k) for k in kwargs} try: for k, v in kwargs.items(): if v is not None: os.environ[k] = v else: del os.environ[k] yield finally: for k, v in old_values.items(): if v is not None: os.environ[k] = v else: del os.environ[k] def _test_parse_config_file( expected_result, config_file_contents='', config_file_paths=None, home=None, xdg_config_home=None, config_file_param=None): # expected_result: (config_file_path, is_xdg); config isn't compared. # config_file_contents: str # config_file_paths: list of filenames to write config_file_contents to # home: str, override HOME env var; default: path of the temporary dir # xdg_config_home: str, set XDG_CONFIG_HOME # config_file_param: str, filename to pass to parse_config_file # All paths starting with '$TMPTESTDIR/' get evaluated relative to the temp dir. if not config_file_paths: config_file_paths = [] with tempfile.TemporaryDirectory() as tmp_test_dir: def _replace_path(s): if s and s.startswith('$TMPTESTDIR/'): return os.path.join(tmp_test_dir, s.split('/', 1)[1]) return s expected_result = (_replace_path(expected_result[0]), expected_result[1]) config_file_paths = [_replace_path(x) for x in config_file_paths] home = _replace_path(home) xdg_config_home = _replace_path(xdg_config_home) config_file_param = _replace_path(config_file_param) for p in config_file_paths: os.makedirs(os.path.dirname(p), exist_ok=True) with open(p, 'w') as fp: fp.write(config_file_contents) if home is None: home = tmp_test_dir env = {'HOME': home} if xdg_config_home is not None: env['XDG_CONFIG_HOME'] = xdg_config_home with _environ(**env): config_file_path, is_xdg, config = internetarchive.config.parse_config_file( config_file=config_file_param) assert (config_file_path, is_xdg) == expected_result[0:2] def test_parse_config_file_blank(): _test_parse_config_file( expected_result=('$TMPTESTDIR/.config/internetarchive/ia.ini', True) ) def test_parse_config_file_existing_config_ia(): _test_parse_config_file( expected_result=('$TMPTESTDIR/.config/ia.ini', False), config_file_paths=['$TMPTESTDIR/.config/ia.ini'], ) def test_parse_config_file_existing_dotia(): _test_parse_config_file( expected_result=('$TMPTESTDIR/.ia', False), config_file_paths=['$TMPTESTDIR/.ia'], ) def test_parse_config_file_existing_config_ia_and_dotia(): _test_parse_config_file( expected_result=('$TMPTESTDIR/.config/ia.ini', False), config_file_paths=['$TMPTESTDIR/.config/ia.ini', '$TMPTESTDIR/.ia'], ) def test_parse_config_file_existing_all(): _test_parse_config_file( expected_result=('$TMPTESTDIR/.config/internetarchive/ia.ini', True), config_file_paths=[ '$TMPTESTDIR/.config/internetarchive/ia.ini', '$TMPTESTDIR/.config/ia.ini', '$TMPTESTDIR/.ia' ], ) def test_parse_config_file_custom_xdg(): _test_parse_config_file( expected_result=('$TMPTESTDIR/.xdg/internetarchive/ia.ini', True), xdg_config_home='$TMPTESTDIR/.xdg', ) def test_parse_config_file_empty_xdg(): # Empty XDG_CONFIG_HOME should be treated as if not set, i.e. default _test_parse_config_file( expected_result=('$TMPTESTDIR/.config/internetarchive/ia.ini', True), xdg_config_home='', ) def test_parse_config_file_relative_xdg(): # Relative XDG_CONFIG_HOME is invalid and should be ignored, i.e. default ~/.config used instead _test_parse_config_file( expected_result=('$TMPTESTDIR/.config/internetarchive/ia.ini', True), xdg_config_home='relative/.config', ) def test_parse_config_file_direct_path_overrides_existing_files(): _test_parse_config_file( expected_result=('/path/to/ia.ini', False), config_file_paths=[ '$TMPTESTDIR/.config/internetarchive/ia.ini', '$TMPTESTDIR/.config/ia.ini', '$TMPTESTDIR/.ia' ], config_file_param='/path/to/ia.ini', ) def test_parse_config_file_with_environment_variable(): with _environ(IA_CONFIG_FILE='/inexistent.ia.ini'): _test_parse_config_file( expected_result=('/inexistent.ia.ini', False), ) def test_parse_config_file_with_environment_variable_and_parameter(): with _environ(IA_CONFIG_FILE='/inexistent.ia.ini'): _test_parse_config_file( expected_result=('/inexistent.other.ia.ini', False), config_file_param='/inexistent.other.ia.ini', ) def _test_write_config_file( expected_config_file, expected_modes, dirs=None, create_expected_file=False, config_file_param=None): # expected_config_file: str # expected_modes: list of (path, mode) tuples # dirs: list of str, directories to create before running write_config_file # create_expected_file: bool, create the expected_config_file if True # config_file_param: str, filename to pass to write_config_file # Both dirs and the config file are created with mode 777 (minus umask). # All paths are evaluated relative to a temporary HOME. # Mode comparison accounts for the umask; expected_modes does not need to care about it. with tempfile.TemporaryDirectory() as temp_home_dir: expected_config_file = os.path.join(temp_home_dir, expected_config_file) if dirs: dirs = [os.path.join(temp_home_dir, d) for d in dirs] expected_modes = [(os.path.join(temp_home_dir, p), m) for p, m in expected_modes] if config_file_param: config_file_param = os.path.join(temp_home_dir, config_file_param) with _environ(HOME=temp_home_dir): # Need to account for the umask in the expected_modes comparisons. # The umask can't just be retrieved, so set and then restore previous value. umask = os.umask(0) os.umask(umask) if dirs: for d in dirs: os.mkdir(d) if create_expected_file: with open(expected_config_file, 'w') as fp: os.chmod(expected_config_file, 0o777) config_file = internetarchive.config.write_config_file({}, config_file_param) assert config_file == expected_config_file assert os.path.isfile(config_file) for path, mode in expected_modes: actual_mode = os.stat(path).st_mode & 0o777 assert actual_mode == mode & ~umask def test_write_config_file_blank(): """Test that a blank HOME is populated with expected dirs and modes.""" _test_write_config_file( expected_config_file='.config/internetarchive/ia.ini', expected_modes=[ ('.config/internetarchive/ia.ini', 0o600), ('.config/internetarchive', 0o700), ('.config', 0o700), ], ) def test_write_config_file_config_existing(): """Test that .config's permissions remain but ia gets created correctly.""" _test_write_config_file( dirs=['.config'], expected_config_file='.config/internetarchive/ia.ini', expected_modes=[ ('.config/internetarchive/ia.ini', 0o600), ('.config/internetarchive', 0o700), ('.config', 0o777), ], ) def test_write_config_file_config_internetarchive_existing(): """Test that directory permissions are left as is""" _test_write_config_file( dirs=['.config', '.config/internetarchive'], expected_config_file='.config/internetarchive/ia.ini', expected_modes=[ ('.config/internetarchive/ia.ini', 0o600), ('.config/internetarchive', 0o777), ('.config', 0o777), ], ) def test_write_config_file_existing_file(): """Test that the permissions of the file are forced to 600""" _test_write_config_file( dirs=['.config', '.config/internetarchive'], expected_config_file='.config/internetarchive/ia.ini', create_expected_file=True, expected_modes=[ ('.config/internetarchive/ia.ini', 0o600), ('.config/internetarchive', 0o777), ('.config', 0o777), ], ) def test_write_config_file_existing_other_file(): """Test that the permissions of the file are forced to 600 even outside XDG""" _test_write_config_file( dirs=['foo'], expected_config_file='foo/ia.ini', create_expected_file=True, config_file_param='foo/ia.ini', expected_modes=[ ('foo/ia.ini', 0o600), ('foo', 0o777), ], ) def test_write_config_file_custom_path_existing(): """Test the creation of a config file at a custom location""" _test_write_config_file( dirs=['foo'], expected_config_file='foo/ia.ini', config_file_param='foo/ia.ini', expected_modes=[ ('foo/ia.ini', 0o600), ('foo', 0o777), ], ) def test_write_config_file_custom_path_not_existing(): """Ensure that an exception is thrown if the custom path dir doesn't exist""" with tempfile.TemporaryDirectory() as temp_home_dir: with _environ(HOME=temp_home_dir): config_file = os.path.join(temp_home_dir, 'foo/ia.ini') with pytest.raises(IOError): internetarchive.config.write_config_file({}, config_file)
14,898
Python
.py
363
32.352617
100
0.606501
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,441
test_ia.py
jjjake_internetarchive/tests/cli/test_ia.py
from tests.conftest import ia_call def test_ia(capsys): ia_call(['ia', '--help']) out, err = capsys.readouterr() assert 'A command line interface to Archive.org.' in out ia_call(['ia', '--insecure', 'ls', 'nasa']) ia_call(['ia', 'nocmd'], expected_exit_code=127) out, err = capsys.readouterr() assert "error: 'nocmd' is not an ia command!" in err ia_call(['ia', 'help']) out, err = capsys.readouterr() assert 'A command line interface to Archive.org.' in err ia_call(['ia', 'help', 'list'])
541
Python
.py
13
36.769231
60
0.630268
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,442
test_ia_download.py
jjjake_internetarchive/tests/cli/test_ia_download.py
import os import sys import time import pytest from tests.conftest import NASA_EXPECTED_FILES, call_cmd, files_downloaded def test_no_args(tmpdir_ch): call_cmd('ia --insecure download nasa') assert files_downloaded(path='nasa') == NASA_EXPECTED_FILES @pytest.mark.xfail("CI" in os.environ, reason="May timeout on continuous integration") def test_https(tmpdir_ch): call_cmd('ia download nasa') assert files_downloaded(path='nasa') == NASA_EXPECTED_FILES def test_dry_run(): nasa_url = 'http://archive.org/download/nasa/' expected_urls = {nasa_url + f for f in NASA_EXPECTED_FILES} stdout, stderr = call_cmd('ia --insecure download --dry-run nasa') output_lines = stdout.split('\n') dry_run_urls = {x.strip() for x in output_lines if x and 'nasa:' not in x} assert expected_urls == dry_run_urls def test_glob(tmpdir_ch): expected_files = { 'globe_west_540.jpg', 'globe_west_540_thumb.jpg', 'nasa_itemimage.jpg', '__ia_thumb.jpg', } call_cmd('ia --insecure download --glob="*jpg" nasa') assert files_downloaded(path='nasa') == expected_files def test_exclude(tmpdir_ch): expected_files = { 'globe_west_540.jpg', 'nasa_itemimage.jpg', } call_cmd('ia --insecure download --glob="*jpg" --exclude="*thumb*" nasa') assert files_downloaded(path='nasa') == expected_files def test_format(tmpdir_ch): call_cmd('ia --insecure download --format="Archive BitTorrent" nasa') assert files_downloaded(path='nasa') == {'nasa_archive.torrent'} def test_on_the_fly_format(): i = 'wonderfulwizardo00baumiala' stdout, stderr = call_cmd(f'ia --insecure download --dry-run --format="DAISY" {i}') assert stdout == '' stdout, stderr = call_cmd(f'ia --insecure download --dry-run --format="DAISY" --on-the-fly {i}') assert stdout == f'http://archive.org/download/{i}/{i}_daisy.zip' def test_clobber(tmpdir_ch): cmd = 'ia --insecure download nasa nasa_meta.xml' call_cmd(cmd) assert files_downloaded('nasa') == {'nasa_meta.xml'} stdout, stderr = call_cmd(cmd) assert files_downloaded('nasa') == {'nasa_meta.xml'} prefix = 'nasa:\n'.replace('\n', os.linesep) filepath = os.path.join('nasa', 'nasa_meta.xml') expected_stderr = f'{prefix} skipping {filepath}, file already exists based on length and date.' assert expected_stderr == stderr def test_checksum(tmpdir_ch): call_cmd('ia --insecure download nasa nasa_meta.xml') assert files_downloaded('nasa') == {'nasa_meta.xml'} stdout, stderr = call_cmd('ia --insecure download --checksum nasa nasa_meta.xml') assert files_downloaded('nasa') == {'nasa_meta.xml'} prefix = 'nasa:\n'.replace('\n', os.linesep) filepath = os.path.join('nasa', 'nasa_meta.xml') assert f'{prefix} skipping {filepath}, file already exists based on checksum.' == stderr def test_checksum_archive(tmpdir_ch): call_cmd('ia --insecure download nasa nasa_meta.xml') assert files_downloaded('nasa') == {'nasa_meta.xml'} stdout, stderr = call_cmd('ia --insecure download --checksum-archive nasa nasa_meta.xml') assert files_downloaded('nasa') == {'nasa_meta.xml'} prefix = 'nasa:\n'.replace('\n', os.linesep) filepath = os.path.join('nasa', 'nasa_meta.xml') assert f'{prefix} skipping {filepath}, file already exists based on checksum.' == stderr assert '_checksum_archive.txt' in files_downloaded('.') with open(os.path.join('.', '_checksum_archive.txt'), encoding='utf-8') as f: filepath = os.path.join('nasa', 'nasa_meta.xml') assert f.read() == f'{filepath}\n' stdout, stderr = call_cmd('ia --insecure download --checksum-archive nasa nasa_meta.xml') assert files_downloaded('nasa') == {'nasa_meta.xml'} prefix = 'nasa:\n'.replace('\n', os.linesep) filepath = os.path.join('nasa', 'nasa_meta.xml') assert f'{prefix} skipping {filepath}, file already exists based on checksum_archive.' == stderr def test_no_directories(tmpdir_ch): call_cmd('ia --insecure download --no-directories nasa nasa_meta.xml') assert files_downloaded('.') == {'nasa_meta.xml'} def test_destdir(tmpdir_ch): cmd = 'ia --insecure download --destdir=thisdirdoesnotexist/ nasa nasa_meta.xml' stdout, stderr = call_cmd(cmd, expected_exit_code=1) assert '--destdir must be a valid path to a directory.' in stderr tmpdir_ch.mkdir('thisdirdoesnotexist/') call_cmd(cmd) assert files_downloaded('thisdirdoesnotexist/nasa') == {'nasa_meta.xml'} tmpdir_ch.mkdir('dir2/') cmd = ('ia --insecure download --no-directories --destdir=dir2/ ' 'nasa nasa_meta.xml') call_cmd(cmd) assert files_downloaded('dir2') == {'nasa_meta.xml'} def test_no_change_timestamp(tmpdir_ch): # TODO: Handle the case of daylight savings time now = time.time() call_cmd('ia --insecure download --no-change-timestamp nasa') for path, dirnames, filenames in os.walk(str(tmpdir_ch)): for d in dirnames: p = os.path.join(path, d) assert os.stat(p).st_mtime >= now for f in filenames: p = os.path.join(path, f) assert os.stat(p).st_mtime >= now
5,236
Python
.py
105
44.409524
100
0.670075
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,443
test_ia_upload.py
jjjake_internetarchive/tests/cli/test_ia_upload.py
import os import sys from contextlib import contextmanager from io import StringIO import responses from internetarchive.utils import json from tests.conftest import IaRequestsMock, ia_call, load_test_data_file PROTOCOL = 'https:' STATUS_CHECK_RESPONSE = load_test_data_file('s3_status_check.json') def test_ia_upload(tmpdir_ch, caplog): with open('test.txt', 'w') as fh: fh.write('foo') with IaRequestsMock() as rsps: rsps.add_metadata_mock('nasa') rsps.add(responses.PUT, f'{PROTOCOL}//s3.us.archive.org/nasa/test.txt', body='', content_type='text/plain') ia_call(['ia', '--log', 'upload', 'nasa', 'test.txt']) assert f'uploaded test.txt to {PROTOCOL}//s3.us.archive.org/nasa/test.txt' in caplog.text def test_ia_upload_invalid_identifier(capsys, caplog): with open('test.txt', 'w') as fh: fh.write('foo') ia_call(['ia', '--log', 'upload', 'føø', 'test.txt'], expected_exit_code=1) out, err = capsys.readouterr() assert ('<identifier> should be between 3 and 80 characters in length, and ' 'can only contain alphanumeric characters, periods ".", ' 'underscores "_", or dashes "-". However, <identifier> cannot begin ' 'with periods, underscores, or dashes.') in err def test_ia_upload_status_check(capsys): with IaRequestsMock() as rsps: rsps.add(responses.GET, f'{PROTOCOL}//s3.us.archive.org', body=STATUS_CHECK_RESPONSE, content_type='application/json') ia_call(['ia', 'upload', 'nasa', '--status-check']) out, err = capsys.readouterr() assert 'success: nasa is accepting requests.' in err j = json.loads(STATUS_CHECK_RESPONSE) j['over_limit'] = 1 rsps.reset() rsps.add(responses.GET, f'{PROTOCOL}//s3.us.archive.org', body=json.dumps(j), content_type='application/json') ia_call(['ia', 'upload', 'nasa', '--status-check'], expected_exit_code=1) out, err = capsys.readouterr() assert ('warning: nasa is over limit, and not accepting requests. ' 'Expect 503 SlowDown errors.') in err def test_ia_upload_debug(capsys, tmpdir_ch, nasa_mocker): with open('test.txt', 'w') as fh: fh.write('foo') ia_call(['ia', 'upload', '--debug', 'nasa', 'test.txt']) out, err = capsys.readouterr() assert 'User-Agent' in err assert 's3.us.archive.org/nasa/test.txt' in err assert 'Accept:*/*' in err assert 'Authorization:LOW ' in err assert 'Connection:close' in err assert 'Content-Length:3' in err assert 'Accept-Encoding:gzip, deflate' in err def test_ia_upload_403(capsys): s3_error = ('<Error>' '<Code>SignatureDoesNotMatch</Code>' '<Message>The request signature we calculated does not match ' 'the signature you provided. Check your AWS Secret Access Key ' 'and signing method. For more information, see REST ' 'Authentication and SOAP Authentication for details.</Message>' "<Resource>'PUT\n\n\n\n/iacli-test-item60/test-replace.txt'</Resource>" '<RequestId>18a9c5ea-088f-42f5-9fcf-70651cc085ca</RequestId>' '</Error>') with IaRequestsMock() as rsps: rsps.add_metadata_mock('nasa') rsps.add(responses.PUT, f'{PROTOCOL}//s3.us.archive.org/nasa/test_ia_upload.py', body=s3_error, status=403, content_type='text/plain') ia_call(['ia', 'upload', 'nasa', __file__], expected_exit_code=1) out, err = capsys.readouterr() assert 'error uploading test_ia_upload.py' in err def test_ia_upload_invalid_cmd(capsys): ia_call(['ia', 'upload', 'nasa', 'nofile.txt'], expected_exit_code=1) out, err = capsys.readouterr() assert '<file> should be a readable file or directory.' in err def test_ia_upload_size_hint(capsys, tmpdir_ch, nasa_mocker): with open('test.txt', 'w') as fh: fh.write('foo') ia_call(['ia', 'upload', '--debug', 'nasa', '--size-hint', '30', 'test.txt']) out, err = capsys.readouterr() assert 'User-Agent' in err assert 's3.us.archive.org/nasa/test.txt' in err assert 'x-archive-size-hint:30' in err assert 'Accept:*/*' in err assert 'Authorization:LOW ' in err assert 'Connection:close' in err assert 'Content-Length:3' in err assert 'Accept-Encoding:gzip, deflate' in err def test_ia_upload_automatic_size_hint_files(capsys, tmpdir_ch, nasa_mocker): with open('foo', 'w') as fh: fh.write('foo') with open('bar', 'w') as fh: fh.write('bar') ia_call(['ia', 'upload', '--debug', 'nasa', 'foo', 'bar']) out, err = capsys.readouterr() assert 'x-archive-size-hint:6' in err def test_ia_upload_automatic_size_hint_dir(capsys, tmpdir_ch, nasa_mocker): with open('foo', 'w') as fh: fh.write('foo') with open('bar', 'w') as fh: fh.write('bar') ia_call(['ia', 'upload', '--debug', 'nasa', '.']) out, err = capsys.readouterr() assert 'x-archive-size-hint:6' in err def test_ia_upload_unicode(tmpdir_ch, caplog): with open('தமிழ் - baz ∆.txt', 'w') as fh: fh.write('unicode foo') efname = '%E0%AE%A4%E0%AE%AE%E0%AE%BF%E0%AE%B4%E0%AF%8D%20-%20baz%20%E2%88%86.txt' with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add_metadata_mock('nasa') rsps.add(responses.PUT, f'{PROTOCOL}//s3.us.archive.org/nasa/{efname}', body='', content_type='text/plain') ia_call(['ia', '--log', 'upload', 'nasa', 'தமிழ் - baz ∆.txt', '--metadata', 'foo:∆']) assert (f'uploaded தமிழ் - baz ∆.txt to {PROTOCOL}//s3.us.archive.org/nasa/' '%E0%AE%A4%E0%AE%AE%E0%AE%BF%E0%AE%B4%E0%AF%8D%20-%20' 'baz%20%E2%88%86.txt') in caplog.text def test_ia_upload_remote_name(tmpdir_ch, caplog): with open('test.txt', 'w') as fh: fh.write('foo') with IaRequestsMock() as rsps: rsps.add_metadata_mock('nasa') rsps.add(responses.PUT, f'{PROTOCOL}//s3.us.archive.org/nasa/hi.txt', body='', content_type='text/plain') ia_call(['ia', '--log', 'upload', 'nasa', 'test.txt', '--remote-name', 'hi.txt']) assert f'uploaded hi.txt to {PROTOCOL}//s3.us.archive.org/nasa/hi.txt' in caplog.text def test_ia_upload_stdin(tmpdir_ch, caplog): @contextmanager def replace_stdin(f): original_stdin = sys.stdin sys.stdin = f try: yield finally: sys.stdin = original_stdin with IaRequestsMock() as rsps: rsps.add_metadata_mock('nasa') rsps.add(responses.PUT, f'{PROTOCOL}//s3.us.archive.org/nasa/hi.txt', body='', content_type='text/plain') with replace_stdin(StringIO('foo')): ia_call(['ia', '--log', 'upload', 'nasa', '-', '--remote-name', 'hi.txt']) assert f'uploaded hi.txt to {PROTOCOL}//s3.us.archive.org/nasa/hi.txt' in caplog.text def test_ia_upload_inexistent_file(tmpdir_ch, capsys, caplog): ia_call(['ia', 'upload', 'foo', 'test.txt'], expected_exit_code=1) out, err = capsys.readouterr() assert '<file> should be a readable file or directory.' in err def test_ia_upload_spreadsheet(tmpdir_ch, caplog): with open('foo.txt', 'w') as fh: fh.write('foo') with open('test.txt', 'w') as fh: fh.write('bar') with open('test.csv', 'w') as fh: fh.write('identifier,file,REMOTE_NAME\n') fh.write('nasa,foo.txt,\n') fh.write(',test.txt,bar.txt\n') with IaRequestsMock() as rsps: rsps.add_metadata_mock('nasa') rsps.add(responses.PUT, f'{PROTOCOL}//s3.us.archive.org/nasa/foo.txt', body='', content_type='text/plain') rsps.add(responses.PUT, f'{PROTOCOL}//s3.us.archive.org/nasa/bar.txt', body='', content_type='text/plain') ia_call(['ia', 'upload', '--spreadsheet', 'test.csv']) assert f'uploaded foo.txt to {PROTOCOL}//s3.us.archive.org/nasa/foo.txt' in caplog.text assert f'uploaded bar.txt to {PROTOCOL}//s3.us.archive.org/nasa/bar.txt' in caplog.text def test_ia_upload_spreadsheet_item_column(tmpdir_ch, caplog): with open('test.txt', 'w') as fh: fh.write('foo') with open('test.csv', 'w') as fh: fh.write('item,file\n') fh.write('nasa,test.txt\n') with IaRequestsMock() as rsps: rsps.add_metadata_mock('nasa') rsps.add(responses.PUT, f'{PROTOCOL}//s3.us.archive.org/nasa/test.txt', body='', content_type='text/plain') ia_call(['ia', 'upload', '--spreadsheet', 'test.csv']) assert f'uploaded test.txt to {PROTOCOL}//s3.us.archive.org/nasa/test.txt' in caplog.text def test_ia_upload_spreadsheet_item_and_identifier_column(tmpdir_ch, caplog): # item is preferred, and both are discarded with open('test.txt', 'w') as fh: fh.write('foo') with open('test.csv', 'w') as fh: fh.write('item,identifier,file\n') fh.write('nasa,uhoh,test.txt\n') with IaRequestsMock() as rsps: rsps.add_metadata_mock('nasa') rsps.add(responses.PUT, f'{PROTOCOL}//s3.us.archive.org/nasa/test.txt', body='', content_type='text/plain') ia_call(['ia', 'upload', '--spreadsheet', 'test.csv']) # Verify that the item and identifier columns are not in the PUT request headers putCalls = [c for c in rsps.calls if c.request.method == 'PUT'] assert len(putCalls) == 1 assert 'x-archive-meta00-identifier' not in putCalls[0].request.headers assert 'x-archive-meta00-item' not in putCalls[0].request.headers assert f'uploaded test.txt to {PROTOCOL}//s3.us.archive.org/nasa/test.txt' in caplog.text def test_ia_upload_spreadsheet_missing_identifier(tmpdir_ch, capsys, caplog): with open('test.txt', 'w') as fh: fh.write('foo') with open('test.csv', 'w') as fh: fh.write('file\n') fh.write('test.txt\n') ia_call(['ia', 'upload', '--spreadsheet', 'test.csv'], expected_exit_code=1) assert 'error: no identifier column on spreadsheet.' in capsys.readouterr().err def test_ia_upload_spreadsheet_empty_identifier(tmpdir_ch, capsys, caplog): with open('test.txt', 'w') as fh: fh.write('foo') with open('test.csv', 'w') as fh: fh.write('identifier,file\n') fh.write(',test.txt\n') ia_call(['ia', 'upload', '--spreadsheet', 'test.csv'], expected_exit_code=1) assert 'error: no identifier column on spreadsheet.' in capsys.readouterr().err def test_ia_upload_spreadsheet_bom(tmpdir_ch, caplog): with open('test.txt', 'w') as fh: fh.write('foo') with open('test.csv', 'wb') as fh: fh.write(b'\xef\xbb\xbf') fh.write(b'identifier,file\n') fh.write(b'nasa,test.txt\n') with IaRequestsMock() as rsps: rsps.add_metadata_mock('nasa') rsps.add(responses.PUT, f'{PROTOCOL}//s3.us.archive.org/nasa/test.txt', body='', content_type='text/plain') ia_call(['ia', 'upload', '--spreadsheet', 'test.csv']) assert f'uploaded test.txt to {PROTOCOL}//s3.us.archive.org/nasa/test.txt' in caplog.text def test_ia_upload_checksum(tmpdir_ch, caplog): with open('test.txt', 'w') as fh: fh.write('foo') # First upload, file not in metadata yet with IaRequestsMock() as rsps: rsps.add_metadata_mock('nasa') rsps.add(responses.PUT, f'{PROTOCOL}//s3.us.archive.org/nasa/test.txt', body='', content_type='text/plain') ia_call(['ia', '--log', 'upload', 'nasa', 'test.txt', '--checksum']) assert f'uploaded test.txt to {PROTOCOL}//s3.us.archive.org/nasa/test.txt' in caplog.text caplog.clear() # Second upload with file in metadata def insert_test_txt(body): body = json.loads(body) body['files'].append({'name': 'test.txt', 'md5': 'acbd18db4cc2f85cedef654fccc4a4d8'}) return json.dumps(body) with IaRequestsMock() as rsps: rsps.add_metadata_mock('nasa', transform_body=insert_test_txt) ia_call(['ia', '--log', 'upload', 'nasa', 'test.txt', '--checksum'], expected_exit_code=1) assert f'test.txt already exists: {PROTOCOL}//s3.us.archive.org/nasa/test.txt' in caplog.text caplog.clear() # Second upload with spreadsheet with open('test.csv', 'w') as fh: fh.write('identifier,file\n') fh.write('nasa,test.txt\n') with IaRequestsMock() as rsps: rsps.add_metadata_mock('nasa', transform_body=insert_test_txt) ia_call(['ia', '--log', 'upload', '--spreadsheet', 'test.csv', '--checksum'], expected_exit_code=1) assert f'test.txt already exists: {PROTOCOL}//s3.us.archive.org/nasa/test.txt' in caplog.text def test_ia_upload_keep_directories(tmpdir_ch, caplog): os.mkdir('foo') with open('foo/test.txt', 'w') as fh: fh.write('foo') with open('test.csv', 'w') as fh: fh.write('identifier,file\n') fh.write('nasa,foo/test.txt\n') # Default behaviour with IaRequestsMock() as rsps: rsps.add_metadata_mock('nasa') rsps.add(responses.PUT, f'{PROTOCOL}//s3.us.archive.org/nasa/test.txt', body='', content_type='text/plain') ia_call(['ia', '--log', 'upload', 'nasa', 'foo/test.txt']) assert f'uploaded test.txt to {PROTOCOL}//s3.us.archive.org/nasa/test.txt' in caplog.text caplog.clear() with IaRequestsMock() as rsps: rsps.add_metadata_mock('nasa') rsps.add(responses.PUT, f'{PROTOCOL}//s3.us.archive.org/nasa/test.txt', body='', content_type='text/plain') ia_call(['ia', '--log', 'upload', '--spreadsheet', 'test.csv']) assert f'uploaded test.txt to {PROTOCOL}//s3.us.archive.org/nasa/test.txt' in caplog.text caplog.clear() # With the option with IaRequestsMock() as rsps: rsps.add_metadata_mock('nasa') rsps.add(responses.PUT, f'{PROTOCOL}//s3.us.archive.org/nasa/foo/test.txt', body='', content_type='text/plain') ia_call(['ia', '--log', 'upload', 'nasa', 'foo/test.txt', '--keep-directories']) assert f'uploaded foo/test.txt to {PROTOCOL}//s3.us.archive.org/nasa/foo/test.txt' in caplog.text caplog.clear() with IaRequestsMock() as rsps: rsps.add_metadata_mock('nasa') rsps.add(responses.PUT, f'{PROTOCOL}//s3.us.archive.org/nasa/foo/test.txt', body='', content_type='text/plain') ia_call(['ia', '--log', 'upload', '--spreadsheet', 'test.csv', '--keep-directories']) assert f'uploaded foo/test.txt to {PROTOCOL}//s3.us.archive.org/nasa/foo/test.txt' in caplog.text
15,221
Python
.py
312
40.141026
101
0.612491
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,444
test_ia_search.py
jjjake_internetarchive/tests/cli/test_ia_search.py
import responses from internetarchive.utils import json from tests.conftest import PROTOCOL, IaRequestsMock, ia_call, load_test_data_file def test_ia_search_itemlist(capsys): test_scrape_response = load_test_data_file('scrape_response.json') with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: url = f'{PROTOCOL}//archive.org/services/search/v1/scrape' p1 = { 'q': 'collection:attentionkmartshoppers', 'count': '10000' } _j = json.loads(test_scrape_response) del _j['cursor'] _r = json.dumps(_j) rsps.add(responses.POST, url, body=_r, match=[responses.matchers.query_param_matcher(p1)]) ia_call(['ia', 'search', 'collection:attentionkmartshoppers', '--itemlist']) out, err = capsys.readouterr() assert len(set(out.split())) == 100 def test_ia_search_num_found(capsys): with IaRequestsMock(assert_all_requests_are_fired=False) as rsps: url = f'{PROTOCOL}//archive.org/services/search/v1/scrape' p = { 'q': 'collection:nasa', 'total_only': 'true', 'count': '10000' } rsps.add(responses.POST, url, body='{"items":[],"count":0,"total":50}', match=[responses.matchers.query_param_matcher(p)]) ia_call(['ia', 'search', 'collection:nasa', '--num-found']) out, err = capsys.readouterr() assert out == '50\n'
1,490
Python
.py
34
34.941176
84
0.611188
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,445
test_ia_list.py
jjjake_internetarchive/tests/cli/test_ia_list.py
from copy import deepcopy from internetarchive import get_session from internetarchive.cli import ia_list from tests.conftest import IaRequestsMock SESSION = get_session() NASA_FILES = { 'NASAarchiveLogo.jpg', 'globe_west_540.jpg', 'nasa_reviews.xml', 'nasa_meta.xml', 'nasa_archive.torrent', 'nasa_files.xml' } def test_ia_list(capsys, nasa_mocker): ia_list.main(['list', 'nasa'], SESSION) out, err = capsys.readouterr() assert {l for l in out.split('\n') if l} == NASA_FILES def test_ia_list_verbose(capsys, nasa_mocker): ia_list.main(['list', '--verbose', 'nasa'], SESSION) out, err = capsys.readouterr() _nasa_files = deepcopy(NASA_FILES) _nasa_files.add('name') assert {l for l in out.split('\n') if l} == _nasa_files def test_ia_list_all(capsys, nasa_mocker): ia_list.main(['list', '--all', 'nasa'], SESSION) out, err = capsys.readouterr() out = [l for l in out.split('\n') if l] assert len(out) == 6 assert all(len(f.split('\t')) == 9 for f in out) assert all(f.split('\t')[0] in NASA_FILES for f in out) def test_ia_list_location(capsys, nasa_mocker): ia_list.main(['list', '--location', '--glob', '*meta.xml', 'nasa'], SESSION) out, err = capsys.readouterr() assert out == 'https://archive.org/download/nasa/nasa_meta.xml\n' def test_ia_list_columns(capsys): with IaRequestsMock() as rsps: rsps.add_metadata_mock('nasa') ia_list.main(['list', '--columns', 'name,md5', '--glob', '*meta.xml', 'nasa'], SESSION) out, err = capsys.readouterr() assert out == 'nasa_meta.xml\t0e339f4a29a8bc42303813cbec9243e5\n' with IaRequestsMock() as rsps: rsps.add_metadata_mock('nasa') ia_list.main(['list', '--columns', 'md5', '--glob', '*meta.xml', 'nasa'], SESSION) out, err = capsys.readouterr() assert out == '0e339f4a29a8bc42303813cbec9243e5\n' def test_ia_list_glob(capsys, nasa_mocker): ia_list.main(['list', '--glob', '*torrent', 'nasa'], SESSION) out, err = capsys.readouterr() assert out == 'nasa_archive.torrent\n' def test_ia_list_format(capsys, nasa_mocker): ia_list.main(['list', '--format', 'Metadata', 'nasa'], SESSION) out, err = capsys.readouterr() expected_output = { 'nasa_reviews.xml', 'nasa_files.xml', 'nasa_meta.xml', } assert {f for f in out.split('\n') if f} == expected_output def test_ia_list_non_existing(capsys): with IaRequestsMock() as rsps: rsps.add_metadata_mock('nasa', body='{}') try: ia_list.main(['list', 'nasa'], SESSION) except SystemExit as exc: assert exc.code == 1 out, err = capsys.readouterr() assert out == ''
2,759
Python
.py
68
35
90
0.633396
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,446
test_ia_metadata.py
jjjake_internetarchive/tests/cli/test_ia_metadata.py
import sys from time import time import responses from tests.conftest import IaRequestsMock, ia_call def test_ia_metadata_exists(capsys): with IaRequestsMock() as rsps: rsps.add_metadata_mock('nasa') ia_call(['ia', 'metadata', '--exists', 'nasa'], expected_exit_code=0) out, err = capsys.readouterr() assert err == 'nasa exists\n' rsps.reset() rsps.add_metadata_mock('nasa', '{}') sys.argv = ['ia', 'metadata', '--exists', 'nasa'] ia_call(['ia', 'metadata', '--exists', 'nasa'], expected_exit_code=1) out, err = capsys.readouterr() assert err == 'nasa does not exist\n' def test_ia_metadata_formats(capsys, nasa_mocker): ia_call(['ia', 'metadata', '--formats', 'nasa']) out, err = capsys.readouterr() expected_formats = {'Collection Header', 'Archive BitTorrent', 'JPEG', 'Metadata', ''} assert set(out.split('\n')) == expected_formats def test_ia_metadata_modify(capsys): md_rsp = ('{"success":true,"task_id":447613301,' '"log":"https://catalogd.archive.org/log/447613301"}') with IaRequestsMock() as rsps: rsps.add_metadata_mock('nasa', method=responses.GET) rsps.add_metadata_mock('nasa', body=md_rsp, method=responses.POST) valid_key = f'foo-{int(time())}' ia_call(['ia', 'metadata', '--modify', f'{valid_key}:test_value', 'nasa']) out, err = capsys.readouterr() assert err == 'nasa - success: https://catalogd.archive.org/log/447613301\n'
1,546
Python
.py
32
41
84
0.619522
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,447
test_argparser.py
jjjake_internetarchive/tests/cli/test_argparser.py
from internetarchive.cli.argparser import get_args_dict def test_get_args_dict(): test_input = [ 'collection:test_collection', 'description: Attention: multiple colons', 'unicode_test:தமிழ்', 'subject:subject1, subject1', 'subject:subject2', 'subject:subject3; subject3', ] test_output = { 'collection': 'test_collection', 'description': ' Attention: multiple colons', 'unicode_test': 'தமிழ்', 'subject': ['subject1, subject1', 'subject2', 'subject3; subject3'], } args_dict = get_args_dict(test_input) for key, value in args_dict.items(): assert test_output[key] == value def test_get_args_dict_query_string(): test_input = ['a=b,foo&c=d&e=f', 'foo:bar '] test_output = { 'a': 'b,foo', 'c': 'd', 'e': 'f', 'foo': 'bar ', } args_dict = get_args_dict(test_input, query_string=True) for key, value in args_dict.items(): assert test_output[key] == value
1,047
Python
.py
30
27.366667
76
0.590131
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,448
lint_python.yml
jjjake_internetarchive/.github/workflows/lint_python.yml
name: lint_python on: [pull_request, push] jobs: lint_python: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: cache: pip python-version: 3.x - run: pip install --upgrade pip setuptools wheel - run: pip install .[all] - run: black --check --skip-string-normalization . || true - run: ruff --format=github . # See pyproject.toml for configuration - run: pip install -r pex-requirements.txt -r tests/requirements.txt - run: mypy . # See setup.cfg for configuration - run: safety check || true # Temporary fix for https://pyup.io/v/51457/f17
681
Python
.pyt
18
31.722222
82
0.641026
jjjake/internetarchive
1,580
217
72
AGPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,449
setup.py
furlongm_openvpn-monitor/setup.py
#!/usr/bin/env python3 import os import sys from setuptools import setup with open('VERSION.txt', 'r') as v: version = v.readline().strip() with open('README.md', 'r') as r: long_description = r.read() for dirpath, dirnames, filenames in os.walk('images/flags'): data_files = [('share/openvpn-monitor/images/flags', [os.path.join(dirpath, f) for f in filenames])] with open('requirements.txt') as rt: install_requires = [] for line in rt.read().splitlines(): if line.endswith("python_version <= '2.7'"): if sys.version_info[0] == 2: install_requires.append(line.split(';')[0]) else: install_requires.append(line) if sys.prefix == '/usr': conf_path = '/etc' else: conf_path = sys.prefix data_files.append((conf_path, ['openvpn-monitor.conf.example'])) setup( name='openvpn-monitor', version=version, author='Marcus Furlong', author_email='furlongm@gmail.com', description=('A simple web based openvpn monitor'), license='GPLv3', keywords='web openvpn monitor', url='http://openvpn-monitor.openbytes.ie', py_modules=['openvpn-monitor', ], install_requires=install_requires, long_description=long_description, long_description_content_type='text/markdown', data_files=data_files, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Application', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', ], )
1,589
Python
.py
45
29.844444
75
0.649967
furlongm/openvpn-monitor
963
293
51
GPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,450
openvpn-monitor.py
furlongm_openvpn-monitor/openvpn-monitor.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2011 VPAC <http://www.vpac.org> # Copyright 2012-2019 Marcus Furlong <furlongm@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 only. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/> from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals try: import ConfigParser as configparser except ImportError: import configparser try: from ipaddr import IPAddress as ip_address except ImportError: from ipaddress import ip_address try: import GeoIP as geoip1 geoip1_available = True except ImportError: geoip1_available = False try: from geoip2 import database from geoip2.errors import AddressNotFoundError geoip2_available = True except ImportError: geoip2_available = False import argparse import os import re import socket import string import sys from datetime import datetime from humanize import naturalsize from collections import OrderedDict, deque from pprint import pformat from semantic_version import Version as semver if sys.version_info[0] == 2: reload(sys) # noqa sys.setdefaultencoding('utf-8') def output(s): global wsgi, wsgi_output if not wsgi: print(s) else: wsgi_output += s def info(*objs): print("INFO:", *objs, file=sys.stderr) def warning(*objs): print("WARNING:", *objs, file=sys.stderr) def debug(*objs): print("DEBUG:\n", *objs, file=sys.stderr) def get_date(date_string, uts=False): if not uts: return datetime.strptime(date_string, "%a %b %d %H:%M:%S %Y") else: return datetime.fromtimestamp(float(date_string)) def get_str(s): if sys.version_info[0] == 2 and s is not None: return s.decode('ISO-8859-1') else: return s def is_truthy(s): return s in ['True', 'true', 'Yes', 'yes', True] class ConfigLoader(object): def __init__(self, config_file): self.settings = {} self.vpns = OrderedDict() config = configparser.RawConfigParser() contents = config.read(config_file) if not contents and config_file == './openvpn-monitor.conf': warning('Config file does not exist or is unreadable: {0!s}'.format(config_file)) if sys.prefix == '/usr': conf_path = '/etc/' else: conf_path = sys.prefix + '/etc/' config_file = conf_path + 'openvpn-monitor.conf' contents = config.read(config_file) if contents: info('Using config file: {0!s}'.format(config_file)) else: warning('Config file does not exist or is unreadable: {0!s}'.format(config_file)) self.load_default_settings() for section in config.sections(): if section.lower() == 'openvpn-monitor': self.parse_global_section(config) else: self.parse_vpn_section(config, section) def load_default_settings(self): info('Using default settings => localhost:5555') self.settings = {'site': 'Default Site', 'maps': 'True', 'geoip_data': '/usr/share/GeoIP/GeoIPCity.dat', 'datetime_format': '%d/%m/%Y %H:%M:%S'} self.vpns['Default VPN'] = {'name': 'default', 'host': 'localhost', 'port': '5555', 'password': '', 'show_disconnect': False} def parse_global_section(self, config): global_vars = ['site', 'logo', 'latitude', 'longitude', 'maps', 'maps_height', 'geoip_data', 'datetime_format'] for var in global_vars: try: self.settings[var] = config.get('openvpn-monitor', var) except configparser.NoSectionError: # backwards compat try: self.settings[var] = config.get('OpenVPN-Monitor', var) except configparser.NoOptionError: pass except configparser.NoOptionError: pass if args.debug: debug("=== begin section\n{0!s}\n=== end section".format(self.settings)) def parse_vpn_section(self, config, section): self.vpns[section] = {} vpn = self.vpns[section] options = config.options(section) for option in options: try: vpn[option] = config.get(section, option) if vpn[option] == -1: warning('CONFIG: skipping {0!s}'.format(option)) except configparser.Error as e: warning('CONFIG: {0!s} on option {1!s}: '.format(e, option)) vpn[option] = None vpn['show_disconnect'] = is_truthy(vpn.get('show_disconnect', False)) if args.debug: debug("=== begin section\n{0!s}\n=== end section".format(vpn)) class OpenvpnMgmtInterface(object): def __init__(self, cfg, **kwargs): self.vpns = cfg.vpns if kwargs.get('vpn_id'): vpn = self.vpns[kwargs['vpn_id']] disconnection_allowed = vpn['show_disconnect'] if disconnection_allowed: self._socket_connect(vpn) if vpn['socket_connected']: release = self.send_command('version\n') version = semver(self.parse_version(release).split(' ')[1]) command = False client_id = int(kwargs.get('client_id')) if version.major == 2 and \ version.minor >= 4 and \ client_id: command = 'client-kill {0!s}\n'.format(client_id) else: ip = ip_address(kwargs['ip']) port = int(kwargs['port']) if ip and port: command = 'kill {0!s}:{1!s}\n'.format(ip, port) if command: self.send_command(command) self._socket_disconnect() geoip_data = cfg.settings['geoip_data'] self.geoip_version = None self.gi = None try: if geoip_data.endswith('.mmdb') and geoip2_available: self.gi = database.Reader(geoip_data) self.geoip_version = 2 elif geoip_data.endswith('.dat') and geoip1_available: self.gi = geoip1.open(geoip_data, geoip1.GEOIP_STANDARD) self.geoip_version = 1 else: warning('No compatible geoip1 or geoip2 data/libraries found.') except IOError: warning('No compatible geoip1 or geoip2 data/libraries found.') for _, vpn in list(self.vpns.items()): self._socket_connect(vpn) if vpn['socket_connected']: self.collect_data(vpn) self._socket_disconnect() def collect_data(self, vpn): ver = self.send_command('version\n') vpn['release'] = self.parse_version(ver) vpn['version'] = semver(vpn['release'].split(' ')[1]) state = self.send_command('state\n') vpn['state'] = self.parse_state(state) stats = self.send_command('load-stats\n') vpn['stats'] = self.parse_stats(stats) status = self.send_command('status 3\n') vpn['sessions'] = self.parse_status(status, vpn['version']) def _socket_send(self, command): if sys.version_info[0] == 2: self.s.send(command) else: self.s.send(bytes(command, 'utf-8')) def _socket_recv(self, length): if sys.version_info[0] == 2: return self.s.recv(length) else: return self.s.recv(length).decode('utf-8') def _socket_connect(self, vpn): timeout = 3 self.s = False try: if vpn.get('socket'): self.s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.s.connect(vpn['socket']) else: host = vpn['host'] port = int(vpn['port']) self.s = socket.create_connection((host, port), timeout) if self.s: password = vpn.get('password') if password: self.wait_for_data(password=password) vpn['socket_connected'] = True except socket.timeout as e: vpn['error'] = '{0!s}'.format(e) warning('socket timeout: {0!s}'.format(e)) vpn['socket_connected'] = False if self.s: self.s.shutdown(socket.SHUT_RDWR) self.s.close() except socket.error as e: vpn['error'] = '{0!s}'.format(e.strerror) warning('socket error: {0!s}'.format(e)) vpn['socket_connected'] = False except Exception as e: vpn['error'] = '{0!s}'.format(e) warning('unexpected error: {0!s}'.format(e)) vpn['socket_connected'] = False def _socket_disconnect(self): self._socket_send('quit\n') self.s.shutdown(socket.SHUT_RDWR) self.s.close() def send_command(self, command): info('Sending command: {0!s}'.format(command)) self._socket_send(command) if command.startswith('kill') or command.startswith('client-kill'): return return self.wait_for_data(command=command) def wait_for_data(self, password=None, command=None): data = '' while 1: socket_data = self._socket_recv(1024) socket_data = re.sub('>INFO(.)*\r\n', '', socket_data) data += socket_data if data.endswith('ENTER PASSWORD:'): if password: self._socket_send('{0!s}\n'.format(password)) else: warning('password requested but no password supplied by configuration') if data.endswith('SUCCESS: password is correct\r\n'): break if command == 'load-stats\n' and data != '': break elif data.endswith("\nEND\r\n"): break if args.debug: debug("=== begin raw data\n{0!s}\n=== end raw data".format(data)) return data @staticmethod def parse_state(data): state = {} for line in data.splitlines(): parts = line.split(',') if args.debug: debug("=== begin split line\n{0!s}\n=== end split line".format(parts)) if parts[0].startswith('>INFO') or \ parts[0].startswith('END') or \ parts[0].startswith('>CLIENT'): continue else: state['up_since'] = get_date(date_string=parts[0], uts=True) state['connected'] = parts[1] state['success'] = parts[2] if parts[3]: state['local_ip'] = ip_address(parts[3]) else: state['local_ip'] = '' if parts[4]: state['remote_ip'] = ip_address(parts[4]) state['mode'] = 'Client' else: state['remote_ip'] = '' state['mode'] = 'Server' return state @staticmethod def parse_stats(data): stats = {} line = re.sub('SUCCESS: ', '', data) parts = line.split(',') if args.debug: debug("=== begin split line\n{0!s}\n=== end split line".format(parts)) stats['nclients'] = int(re.sub('nclients=', '', parts[0])) stats['bytesin'] = int(re.sub('bytesin=', '', parts[1])) stats['bytesout'] = int(re.sub('bytesout=', '', parts[2]).replace('\r\n', '')) return stats def parse_status(self, data, version): gi = self.gi geoip_version = self.geoip_version client_section = False routes_section = False sessions = {} client_session = {} for line in data.splitlines(): parts = deque(line.split('\t')) if args.debug: debug("=== begin split line\n{0!s}\n=== end split line".format(parts)) if parts[0].startswith('END'): break if parts[0].startswith('TITLE') or \ parts[0].startswith('GLOBAL') or \ parts[0].startswith('TIME'): continue if parts[0] == 'HEADER': if parts[1] == 'CLIENT_LIST': client_section = True routes_section = False if parts[1] == 'ROUTING_TABLE': client_section = False routes_section = True continue if parts[0].startswith('TUN') or \ parts[0].startswith('TCP') or \ parts[0].startswith('Auth'): parts = parts[0].split(',') if parts[0] == 'TUN/TAP read bytes': client_session['tuntap_read'] = int(parts[1]) continue if parts[0] == 'TUN/TAP write bytes': client_session['tuntap_write'] = int(parts[1]) continue if parts[0] == 'TCP/UDP read bytes': client_session['tcpudp_read'] = int(parts[1]) continue if parts[0] == 'TCP/UDP write bytes': client_session['tcpudp_write'] = int(parts[1]) continue if parts[0] == 'Auth read bytes': client_session['auth_read'] = int(parts[1]) sessions['Client'] = client_session continue if client_section: session = {} parts.popleft() common_name = parts.popleft() remote_str = parts.popleft() if remote_str.count(':') == 1: remote, port = remote_str.split(':') elif '(' in remote_str: remote, port = remote_str.split('(') port = port[:-1] else: remote = remote_str port = None remote_ip = ip_address(remote) session['remote_ip'] = remote_ip if port: session['port'] = int(port) else: session['port'] = '' if session['remote_ip'].is_private: session['location'] = 'RFC1918' elif session['remote_ip'].is_loopback: session['location'] = 'loopback' else: try: if geoip_version == 1: gir = gi.record_by_addr(str(session['remote_ip'])) if gir is not None: session['location'] = gir['country_code'] session['region'] = get_str(gir['region']) session['city'] = get_str(gir['city']) session['country'] = gir['country_name'] session['longitude'] = gir['longitude'] session['latitude'] = gir['latitude'] elif geoip_version == 2: gir = gi.city(str(session['remote_ip'])) session['location'] = gir.country.iso_code session['region'] = gir.subdivisions.most_specific.iso_code session['city'] = gir.city.name session['country'] = gir.country.name session['longitude'] = gir.location.longitude session['latitude'] = gir.location.latitude except AddressNotFoundError: pass except SystemError: pass local_ipv4 = parts.popleft() if local_ipv4: session['local_ip'] = ip_address(local_ipv4) else: session['local_ip'] = '' if version.major >= 2 and version.minor >= 4: local_ipv6 = parts.popleft() if local_ipv6: session['local_ip'] = ip_address(local_ipv6) session['bytes_recv'] = int(parts.popleft()) session['bytes_sent'] = int(parts.popleft()) parts.popleft() session['connected_since'] = get_date(parts.popleft(), uts=True) username = parts.popleft() if username != 'UNDEF': session['username'] = username else: session['username'] = common_name if version.major == 2 and version.minor >= 4: session['client_id'] = parts.popleft() session['peer_id'] = parts.popleft() sessions[str(session['local_ip'])] = session if routes_section: local_ip = parts[1] remote_ip = parts[3] last_seen = get_date(parts[5], uts=True) if sessions.get(local_ip): sessions[local_ip]['last_seen'] = last_seen elif self.is_mac_address(local_ip): matching_local_ips = [sessions[s]['local_ip'] for s in sessions if remote_ip == self.get_remote_address(sessions[s]['remote_ip'], sessions[s]['port'])] if len(matching_local_ips) == 1: local_ip = '{0!s}'.format(matching_local_ips[0]) if sessions[local_ip].get('last_seen'): prev_last_seen = sessions[local_ip]['last_seen'] if prev_last_seen < last_seen: sessions[local_ip]['last_seen'] = last_seen else: sessions[local_ip]['last_seen'] = last_seen if args.debug: if sessions: pretty_sessions = pformat(sessions) debug("=== begin sessions\n{0!s}\n=== end sessions".format(pretty_sessions)) else: debug("no sessions") return sessions @staticmethod def parse_version(data): for line in data.splitlines(): if line.startswith('OpenVPN'): return line.replace('OpenVPN Version: ', '') @staticmethod def is_mac_address(s): return len(s) == 17 and \ len(s.split(':')) == 6 and \ all(c in string.hexdigits for c in s.replace(':', '')) @staticmethod def get_remote_address(ip, port): if port: return '{0!s}:{1!s}'.format(ip, port) else: return '{0!s}'.format(ip) class OpenvpnHtmlPrinter(object): def __init__(self, cfg, monitor): self.init_vars(cfg.settings, monitor) self.print_html_header() for key, vpn in self.vpns: if vpn['socket_connected']: self.print_vpn(key, vpn) else: self.print_unavailable_vpn(vpn) if self.maps: self.print_maps_html() self.print_html_footer() def init_vars(self, settings, monitor): self.vpns = list(monitor.vpns.items()) self.site = settings.get('site', 'Example') self.logo = settings.get('logo') self.maps = is_truthy(settings.get('maps', False)) if self.maps: self.maps_height = settings.get('maps_height', 500) self.latitude = settings.get('latitude', 40.72) self.longitude = settings.get('longitude', -74) self.datetime_format = settings.get('datetime_format') def print_html_header(self): global wsgi if not wsgi: output("Content-Type: text/html\n") output('<!doctype html>') output('<html lang="en"><head>') output('<meta charset="utf-8">') output('<meta http-equiv="X-UA-Compatible" content="IE=edge">') output('<meta name="viewport" content="width=device-width, initial-scale=1">') output('<title>{0!s} OpenVPN Status Monitor</title>'.format(self.site)) output('<meta http-equiv="refresh" content="300" />') # css output('<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha512-Dop/vW3iOtayerlYAqCgkVr2aTr2ErwwTYOvRFUpzl2VhCMJyjQF0Q9TjUXIo6JhuM/3i0vVEt2e/7QQmnHQqw==" crossorigin="anonymous" />') # noqa output('<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap-theme.min.css" integrity="sha512-iy8EXLW01a00b26BaqJWaCmk9fJ4PsMdgNRqV96KwMPSH+blO82OHzisF/zQbRIIi8m0PiO10dpS0QxrcXsisw==" crossorigin="anonymous" />') # noqa output('<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.3/css/theme.bootstrap_3.min.css" integrity="sha512-1r2gsUynzocV5QbYgEwbcNGYQeQ4jgHUNZLl+PMr6o248376S3f9k8zmXvsKkU06wH0MrmQacKd0BjJ/kWeeng==" crossorigin="anonymous" />') # noqa if self.maps: output('<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.min.css" integrity="sha512-1xoFisiGdy9nvho8EgXuXvnpR5GAMSjFwp40gSRE3NwdUdIMIKuPa7bqoUhLD0O/5tPNhteAsE5XyyMi5reQVA==" crossorigin="anonymous" />') # noqa output('<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/leaflet.fullscreen/2.0.0/Control.FullScreen.min.css" integrity="sha512-DRkMa+fn898M1uc6s9JZeztUoXN6viuHsXmh/pgz3jG6a77YWO3U3QYEjLoqbxOeclc2NunWfMTya4Y5twXAKA==" crossorigin="anonymous" />') # noqa output('<style>') output('.panel-custom {') output(' background-color:#777;') output(' color:#fff;') output(' font-size:80%;') output(' vertical-align:baseline;') output(' padding:.4em .4em .4em;') output(' line-height:1;') output(' font-weight:700;') output('}') output('</style>') # js output('<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>') # noqa output('<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.3/js/jquery.tablesorter.min.js" integrity="sha512-qzgd5cYSZcosqpzpn7zF2ZId8f/8CHmFKZ8j7mU4OUXTNRd5g+ZHBPsgKEwoqxCtdQvExE5LprwwPAgoicguNg==" crossorigin="anonymous"></script>') # noqa output('<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.3/js/jquery.tablesorter.widgets.min.js" integrity="sha512-dj/9K5GRIEZu+Igm9tC16XPOTz0RdPk9FGxfZxShWf65JJNU2TjbElGjuOo3EhwAJRPhJxwEJ5b+/Ouo+VqZdQ==" crossorigin="anonymous"></script>') # noqa output('<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.3/js/parsers/parser-network.min.js" integrity="sha512-13ZRU2LDOsGjGgqBkQPKQ/JwT/SfWhtAeFNEbB0dFG/Uf/D1OJPbTpeK2AedbDnTLYWCB6VhTwLxlD0ws6EqCw==" crossorigin="anonymous"></script>') # noqa output('<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.3/js/parsers/parser-duration.min.js" integrity="sha512-X7QJLLEO6yg8gSlmgRAP7Ec2qDD+ndnFcd8yagZkkN5b/7bCMbhRQdyJ4SjENUEr+4eBzgwvaFH5yR/bLJZJQA==" crossorigin="anonymous"></script>') # noqa output('<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha512-oBTprMeNEKCnqfuqKd6sbvFzmFQtlXS3e0C/RGFV0hD6QzhHV+ODfaQbAlmY6/q0ubbwlAM/nCJjkrgA3waLzg==" crossorigin="anonymous"></script>') # noqa output('<script>$(document).ready(function(){') output('$("table.tablesorter").tablesorter({') output('sortList: [[0,0]], theme:"bootstrap", headerTemplate:"{content} {icon}", widgets:["uitheme"],') output('durationLabels : "(?:years|year|y),(?:days|day|d),(?:hours|hour|h),(?:minutes|minute|min|m),(?:seconds|second|sec|s)"') output('});') output('});</script>') if self.maps: output('<script src="//cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.min.js" integrity="sha512-SeiQaaDh73yrb56sTW/RgVdi/mMqNeM2oBwubFHagc5BkixSpP1fvqF47mKzPGWYSSy4RwbBunrJBQ4Co8fRWA==" crossorigin="anonymous"></script>') # noqa output('<script src="//cdnjs.cloudflare.com/ajax/libs/OverlappingMarkerSpiderfier-Leaflet/0.2.6/oms.min.js" integrity="sha512-V8RRDnS4BZXrat3GIpnWx+XNYBHQGdK6nKOzMpX4R0hz9SPWt7fltGmmyGzUkVFZUQODO1rE+SWYJJkw3SYMhg==" crossorigin="anonymous"></script>') # noqa output('<script src="//cdnjs.cloudflare.com/ajax/libs/leaflet.fullscreen/2.0.0/Control.FullScreen.min.js" integrity="sha512-c6ydt5Rypa1ptlnH2U1u+JybARYppbD1qxgythCI4pJ9EOfNYEWlLBjxBX926O3tq5p4Aw5GTY68vT0FdKbG3w==" crossorigin="anonymous"></script>') # noqa output('</head><body>') output('<nav class="navbar navbar-inverse">') output('<div class="container-fluid">') output('<div class="navbar-header">') output('<button type="button" class="navbar-toggle" ') output('data-toggle="collapse" data-target="#myNavbar">') output('<span class="icon-bar"></span>') output('<span class="icon-bar"></span>') output('<span class="icon-bar"></span>') output('</button>') output('<a class="navbar-brand" href="#">') output('{0!s} OpenVPN Status Monitor</a>'.format(self.site)) output('</div><div class="collapse navbar-collapse" id="myNavbar">') output('<ul class="nav navbar-nav"><li class="dropdown">') output('<a class="dropdown-toggle" data-toggle="dropdown" href="#">VPN') output('<span class="caret"></span></a>') output('<ul class="dropdown-menu">') for _, vpn in self.vpns: if vpn['name']: anchor = vpn['name'].lower().replace(' ', '_') output('<li><a href="#{0!s}">{1!s}</a></li>'.format(anchor, vpn['name'])) output('</ul></li>') if self.maps: output('<li><a href="#map_canvas">Map View</a></li>') output('</ul>') if self.logo: output('<a href="#" class="pull-right"><img alt="Logo" ') output('style="max-height:46px; padding-top:3px;" ') if self.logo.startswith("http"): output('src="{0!s}"></a>'.format(self.logo)) else: output('src="images/{0!s}"></a>'.format(self.logo)) output('</div></div></nav>') output('<div class="container-fluid">') @staticmethod def print_session_table_headers(vpn_mode, show_disconnect): server_headers = ['Username / Hostname', 'VPN IP', 'Remote IP', 'Location', 'Bytes In', 'Bytes Out', 'Connected Since', 'Last Ping', 'Time Online'] if show_disconnect: server_headers.append('Action') client_headers = ['Tun-Tap-Read', 'Tun-Tap-Write', 'TCP-UDP-Read', 'TCP-UDP-Write', 'Auth-Read'] if vpn_mode == 'Client': headers = client_headers elif vpn_mode == 'Server': headers = server_headers output('<div class="table-responsive">') output('<table id="sessions" class="table table-striped table-bordered ') output('table-hover table-condensed table-responsive ') output('tablesorter tablesorter-bootstrap">') output('<thead><tr>') for header in headers: if header == 'Time Online': output('<th class="sorter-duration">{0!s}</th>'.format(header)) else: output('<th>{0!s}</th>'.format(header)) output('</tr></thead><tbody>') @staticmethod def print_session_table_footer(): output('</tbody></table></div>') @staticmethod def print_unavailable_vpn(vpn): anchor = vpn['name'].lower().replace(' ', '_') output('<div class="panel panel-danger" id="{0!s}">'.format(anchor)) output('<div class="panel-heading">') output('<h3 class="panel-title">{0!s}</h3></div>'.format(vpn['name'])) output('<div class="panel-body">') output('Could not connect to ') if vpn.get('host') and vpn.get('port'): output('{0!s}:{1!s} ({2!s})</div></div>'.format(vpn['host'], vpn['port'], vpn['error'])) elif vpn.get('socket'): output('{0!s} ({1!s})</div></div>'.format(vpn['socket'], vpn['error'])) else: warning('failed to get socket or network info: {}'.format(vpn)) output('network or unix socket</div></div>') def print_vpn(self, vpn_id, vpn): if vpn['state']['success'] == 'SUCCESS': pingable = 'Yes' else: pingable = 'No' connection = vpn['state']['connected'] nclients = vpn['stats']['nclients'] bytesin = vpn['stats']['bytesin'] bytesout = vpn['stats']['bytesout'] vpn_mode = vpn['state']['mode'] vpn_sessions = vpn['sessions'] local_ip = vpn['state']['local_ip'] remote_ip = vpn['state']['remote_ip'] up_since = vpn['state']['up_since'] show_disconnect = vpn['show_disconnect'] anchor = vpn['name'].lower().replace(' ', '_') output('<div class="panel panel-success" id="{0!s}">'.format(anchor)) output('<div class="panel-heading"><h3 class="panel-title">{0!s}</h3>'.format( vpn['name'])) output('</div><div class="panel-body">') output('<div class="table-responsive">') output('<table class="table table-condensed table-responsive">') output('<thead><tr><th>VPN Mode</th><th>Status</th><th>Pingable</th>') output('<th>Clients</th><th>Total Bytes In</th><th>Total Bytes Out</th>') output('<th>Up Since</th><th>Local IP Address</th>') if vpn_mode == 'Client': output('<th>Remote IP Address</th>') output('</tr></thead><tbody>') output('<tr><td>{0!s}</td>'.format(vpn_mode)) output('<td>{0!s}</td>'.format(connection)) output('<td>{0!s}</td>'.format(pingable)) output('<td>{0!s}</td>'.format(nclients)) output('<td>{0!s} ({1!s})</td>'.format(bytesin, naturalsize(bytesin, binary=True))) output('<td>{0!s} ({1!s})</td>'.format(bytesout, naturalsize(bytesout, binary=True))) output('<td>{0!s}</td>'.format(up_since.strftime(self.datetime_format))) output('<td>{0!s}</td>'.format(local_ip)) if vpn_mode == 'Client': output('<td>{0!s}</td>'.format(remote_ip)) output('</tr></tbody></table></div>') if vpn_mode == 'Client' or nclients > 0: self.print_session_table_headers(vpn_mode, show_disconnect) self.print_session_table(vpn_id, vpn_mode, vpn_sessions, show_disconnect) self.print_session_table_footer() output('</div>') output('<div class="panel-footer panel-custom">') output('{0!s}'.format(vpn['release'])) output('</div>') output('</div>') @staticmethod def print_client_session(session): tuntap_r = session['tuntap_read'] tuntap_w = session['tuntap_write'] tcpudp_r = session['tcpudp_read'] tcpudp_w = session['tcpudp_write'] auth_r = session['auth_read'] output('<td>{0!s} ({1!s})</td>'.format(tuntap_r, naturalsize(tuntap_r, binary=True))) output('<td>{0!s} ({1!s})</td>'.format(tuntap_w, naturalsize(tuntap_w, binary=True))) output('<td>{0!s} ({1!s})</td>'.format(tcpudp_r, naturalsize(tcpudp_w, binary=True))) output('<td>{0!s} ({1!s})</td>'.format(tcpudp_w, naturalsize(tcpudp_w, binary=True))) output('<td>{0!s} ({1!s})</td>'.format(auth_r, naturalsize(auth_r, binary=True))) def print_server_session(self, vpn_id, session, show_disconnect): total_time = str(datetime.now() - session['connected_since'])[:-7] bytes_recv = session['bytes_recv'] bytes_sent = session['bytes_sent'] output('<td>{0!s}</td>'.format(session['username'])) output('<td>{0!s}</td>'.format(session['local_ip'])) output('<td>{0!s}</td>'.format(session['remote_ip'])) if session.get('location'): flag = 'images/flags/{0!s}.png'.format(session['location'].lower()) if session.get('country'): country = session['country'] full_location = country if session.get('region'): region = session['region'] full_location = '{0!s}, {1!s}'.format(region, full_location) if session.get('city'): city = session['city'] full_location = '{0!s}, {1!s}'.format(city, full_location) if session['location'] in ['RFC1918', 'loopback']: if session['location'] == 'RFC1918': city = 'RFC1918' elif session['location'] == 'loopback': city = 'loopback' country = 'Internet' full_location = '{0!s}, {1!s}'.format(city, country) flag = 'images/flags/rfc.png' output('<td><img src="{0!s}" title="{1!s}" alt="{1!s}" /> '.format(flag, full_location)) output('{0!s}</td>'.format(full_location)) else: output('<td>Unknown</td>') output('<td>{0!s} ({1!s})</td>'.format(bytes_recv, naturalsize(bytes_recv, binary=True))) output('<td>{0!s} ({1!s})</td>'.format(bytes_sent, naturalsize(bytes_sent, binary=True))) output('<td>{0!s}</td>'.format( session['connected_since'].strftime(self.datetime_format))) if session.get('last_seen'): output('<td>{0!s}</td>'.format( session['last_seen'].strftime(self.datetime_format))) else: output('<td>Unknown</td>') output('<td>{0!s}</td>'.format(total_time)) if show_disconnect: output('<td><form method="post">') output('<input type="hidden" name="vpn_id" value="{0!s}">'.format(vpn_id)) if session.get('port'): output('<input type="hidden" name="ip" value="{0!s}">'.format(session['remote_ip'])) output('<input type="hidden" name="port" value="{0!s}">'.format(session['port'])) if session.get('client_id'): output('<input type="hidden" name="client_id" value="{0!s}">'.format(session['client_id'])) output('<button type="submit" class="btn btn-xs btn-danger">') output('<span class="glyphicon glyphicon-remove"></span> ') output('Disconnect</button></form></td>') def print_session_table(self, vpn_id, vpn_mode, sessions, show_disconnect): for _, session in list(sessions.items()): if vpn_mode == 'Client': output('<tr>') self.print_client_session(session) output('</tr>') elif vpn_mode == 'Server' and session['local_ip']: output('<tr>') self.print_server_session(vpn_id, session, show_disconnect) output('</tr>') def print_maps_html(self): output('<div class="panel panel-info"><div class="panel-heading">') output('<h3 class="panel-title">Map View</h3></div><div class="panel-body">') output('<div id="map_canvas" style="height:{0!s}px"></div>'.format(self.maps_height)) output('<script>') output('var map = L.map("map_canvas", { fullscreenControl: true, ' 'fullscreenControlOptions: { position: "topleft" } });') output('var centre = L.latLng({0!s}, {1!s});'.format(self.latitude, self.longitude)) output('map.setView(centre, 8);') output('url = "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png";') output('var layer = new L.TileLayer(url, {});') output('map.addLayer(layer);') output('var bounds = L.latLngBounds(centre);') output('var oms = new OverlappingMarkerSpiderfier ' '(map,{keepSpiderfied:true});') # spiderfy - add popups for closeby icons output('var popup = new L.Popup({closeButton:false,' 'offset:new L.Point(0.5,-24)});') output('oms.addListener("click", function(marker) {') output(' popup.setContent(marker.alt);') output(' popup.setLatLng(marker.getLatLng());') output(' map.openPopup(popup);') output('});') # spiderfy - close popups when clicking elsewhere output('oms.addListener("spiderfy", function(markers) {') output(' map.closePopup();') output('});') for _, vpn in self.vpns: if vpn.get('sessions'): output('bounds.extend(centre);') for _, session in list(vpn['sessions'].items()): if not session.get('local_ip'): continue if session.get('latitude') and session.get('longitude'): output('var latlng = new L.latLng({0!s}, {1!s});'.format( session['latitude'], session['longitude'])) output('bounds.extend(latlng);') output('var client_marker = L.marker(latlng).addTo(map);') output('oms.addMarker(client_marker);') output('var client_popup = L.popup().setLatLng(latlng);') output('client_popup.setContent("{0!s} - {1!s}");'.format( session['username'], session['remote_ip'])) output('client_marker.bindPopup(client_popup);') output('map.fitBounds(bounds);') output('</script>') output('</div></div>') def print_html_footer(self): output('<div class="well well-sm">') output('Page automatically reloads every 5 minutes.') output('Last update: <b>{0!s}</b></div>'.format( datetime.now().strftime(self.datetime_format))) output('</div></body></html>') def main(**kwargs): cfg = ConfigLoader(args.config) monitor = OpenvpnMgmtInterface(cfg, **kwargs) OpenvpnHtmlPrinter(cfg, monitor) if args.debug: pretty_vpns = pformat((dict(monitor.vpns))) debug("=== begin vpns\n{0!s}\n=== end vpns".format(pretty_vpns)) def get_args(): parser = argparse.ArgumentParser( description='Display a html page with openvpn status and connections') parser.add_argument('-d', '--debug', action='store_true', required=False, default=False, help='Run in debug mode') parser.add_argument('-c', '--config', type=str, required=False, default='./openvpn-monitor.conf', help='Path to config file openvpn-monitor.conf') return parser.parse_args() if __name__ == '__main__': args = get_args() wsgi = False main() def monitor_wsgi(): owd = os.getcwd() if owd.endswith('site-packages') and sys.prefix != '/usr': # virtualenv image_dir = owd + '/../../../share/openvpn-monitor/' else: image_dir = '' app = Bottle() def render(**kwargs): global wsgi_output wsgi_output = '' main(**kwargs) response.content_type = 'text/html;' return wsgi_output @app.hook('before_request') def strip_slash(): request.environ['PATH_INFO'] = request.environ.get('PATH_INFO', '/').rstrip('/') if args.debug: debug(pformat(request.environ)) @app.route('/', method='GET') def get_slash(): return render() @app.route('/', method='POST') def post_slash(): vpn_id = request.forms.get('vpn_id') ip = request.forms.get('ip') port = request.forms.get('port') client_id = request.forms.get('client_id') return render(vpn_id=vpn_id, ip=ip, port=port, client_id=client_id) @app.route('/<filename:re:.*\.(jpg|png)>', method='GET') def get_images(filename): return static_file(filename, image_dir) return app if __name__.startswith('_mod_wsgi_') or \ __name__ == 'openvpn-monitor' or \ __name__ == 'uwsgi_file_openvpn-monitor': if __file__ != 'openvpn-monitor.py': os.chdir(os.path.dirname(__file__)) sys.path.append(os.path.dirname(__file__)) from bottle import Bottle, response, request, static_file class args(object): debug = False config = './openvpn-monitor.conf' wsgi = True wsgi_output = '' application = monitor_wsgi()
41,829
Python
.py
845
37.071006
279
0.555431
furlongm/openvpn-monitor
963
293
51
GPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,451
listen.py
furlongm_openvpn-monitor/tests/listen.py
#!/usr/bin/env python import sys import socket import select host = '127.0.0.1' port = 5555 timeout = 3 status = """TITLE OpenVPN 2.3.10 x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [EPOLL] [PKCS11] [MH] [IPv6] built on Jan 4 2016\r TIME Wed Mar 23 21:42:22 2016 1458729742\r HEADER CLIENT_LIST Common Name Real Address Virtual Address Bytes Received Bytes Sent Connected Since Connected Since (time_t) Username\r CLIENT_LIST furlongm ::ffff:59.167.120.210 10.10.10.6 369528 1216150 Wed Mar 23 21:40:15 2016 1458729615 furlongm\r CLIENT_LIST furlongm 59.167.120.211:12345 10.10.10.7 12345 11615 Wed Mar 23 21:41:45 2016 1458729715 furlongm\r CLIENT_LIST furlongm 2001:4860:4801:3::20 10.10.10.8 12345 11615 Wed Mar 23 21:43:25 2016 1458729815 furlongm\r HEADER ROUTING_TABLE Virtual Address Common Name Real Address Last Ref Last Ref (time_t)\r ROUTING_TABLE 10.10.10.6 furlongm ::ffff:59.167.120.210 Wed Mar 23 21:42:22 2016 1458729742\r ROUTING_TABLE 10.10.10.7 furlongm 59.167.120.211:12345 Wed Mar 23 21:42:22 2016 1458729742\r ROUTING_TABLE 10.10.10.8 furlongm 2001:4860:4801:3::20 Wed Mar 23 21:42:22 2016 1458729742\r GLOBAL_STATS Max bcast/mcast queue length 0\r END\r """ state = """1457583275,CONNECTED,SUCCESS,10.10.10.1,\r END\r """ version = """OpenVPN Version: OpenVPN 2.3.10 x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [EPOLL] [PKCS11] [MH] [IPv6] built on Jan 4 2016\r Management Version: 1\r END\r """ stats = """SUCCESS: nclients=1,bytesin=556794,bytesout=1483013\r """ try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((host, port)) s.listen(timeout) except socket.error as e: print('Failed to create socket: {0}').format(e) sys.exit(1) print('[+] Listening for connections on {0}:{1}'.format(host, port)) data = '' received_exit = False while not received_exit: conn, address = s.accept() print('[+] Connection from {0}'.format(address)) while 1: try: readable, writable, exceptional = \ select.select([conn], [conn], [], timeout) except select.error: print('[+] Exception. Closing connection from {0}'.format(address)) conn.shutdown(2) conn.close() break if readable: data = conn.recv(1024) if data.endswith(u'\n'): if data.startswith(u'status 3'): conn.send(status) data = '' elif data.startswith(u'state'): conn.send(state) data = '' elif data.startswith(u'version'): conn.send(version) data = '' elif data.startswith(u'load-stats'): conn.send(stats) data = '' elif data.startswith(u'quit'): print('[+] Closing connection from {0}'.format(address)) conn.shutdown(2) conn.close() data = '' break elif data.startswith(u'exit'): print('[+] Closing connection from {0}'.format(address)) conn.shutdown(2) conn.close() s.close() received_exit = True break else: pass elif readable and writable: print('[+] Closing connection from {0}'.format(address)) conn.shutdown(2) conn.close() break print('[+] Closing socket: {0}:{1}'.format(host, port))
3,555
Python
.py
88
32.295455
138
0.615963
furlongm/openvpn-monitor
963
293
51
GPL-3.0
9/5/2024, 5:12:38 PM (Europe/Amsterdam)
20,452
setup.py
pwr-Solaar_Solaar/setup.py
import subprocess import textwrap from glob import glob from os.path import dirname from pathlib import Path from setuptools import find_packages from setuptools import setup NAME = "Solaar" version = Path("lib/solaar/version").read_text().strip() try: # get commit from git describe commit = subprocess.check_output(["git", "describe", "--always"], stderr=subprocess.DEVNULL).strip().decode() Path("lib/solaar/commit").write_text(f"{commit}\n") except Exception: # get commit from Ubuntu dpkg-parsechangelog try: commit = ( subprocess.check_output(["dpkg-parsechangelog", "--show-field", "Version"], stderr=subprocess.DEVNULL) .strip() .decode() ) commit = commit.split("~") Path("lib/solaar/commit").write_text(f"{commit[0]}\n") except Exception as e: print("Exception using dpkg-parsechangelog", e) def _data_files(): yield "share/icons/hicolor/scalable/apps", glob("share/solaar/icons/solaar*.svg") yield "share/icons/hicolor/32x32/apps", glob("share/solaar/icons/solaar-light_*.png") for mo in glob("share/locale/*/LC_MESSAGES/solaar.mo"): yield dirname(mo), [mo] yield "share/applications", ["share/applications/solaar.desktop"] yield "lib/udev/rules.d", ["rules.d/42-logitech-unify-permissions.rules"] yield "share/metainfo", ["share/solaar/io.github.pwr_solaar.solaar.metainfo.xml"] setup( name=NAME.lower(), version=version, description="Linux device manager for Logitech receivers, keyboards, mice, and tablets.", long_description=textwrap.dedent( """ Solaar is a Linux device manager for many Logitech peripherals that connect through Unifying and other receivers or via USB or Bluetooth. Solaar is able to pair/unpair devices with receivers and show and modify some of the modifiable features of devices. For instructions on installing Solaar see https://pwr-solaar.github.io/Solaar/installation""" ), author="Daniel Pavel", license="GPLv2", url="http://pwr-solaar.github.io/Solaar/", classifiers=[ "Development Status :: 4 - Beta", "Environment :: X11 Applications :: GTK", "Environment :: Console", "Intended Audience :: End Users/Desktop", "License :: DFSG approved", "License :: OSI Approved :: GNU General Public License v2 (GPLv2)", "Natural Language :: English", "Programming Language :: Python :: 3 :: Only", "Operating System :: POSIX :: Linux", "Topic :: Utilities", ], platforms=["linux"], python_requires=">=3.8", install_requires=[ 'evdev (>= 1.1.2) ; platform_system=="Linux"', "pyudev (>= 0.13)", "PyYAML (>= 3.12)", "python-xlib (>= 0.27)", "psutil (>= 5.4.3)", 'dbus-python ; platform_system=="Linux"', "PyGObject", ], extras_require={ "report-descriptor": ["hid-parser"], "desktop-notifications": ["Notify (>= 0.7)"], "git-commit": ["python-git-info"], "test": ["pytest", "pytest-mock", "pytest-cov", "typing_extensions"], "dev": ["ruff"], }, package_dir={"": "lib"}, packages=find_packages(where="lib"), data_files=list(_data_files()), include_package_data=True, scripts=glob("bin/*"), )
3,363
Python
.py
82
34.621951
114
0.642923
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,453
receiver.py
pwr-Solaar_Solaar/lib/logitech_receiver/receiver.py
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/ ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from __future__ import annotations import errno import logging import time import typing from dataclasses import dataclass from typing import Callable from typing import Optional from typing import Protocol from solaar.i18n import _ from solaar.i18n import ngettext from . import exceptions from . import hidpp10 from . import hidpp10_constants from .common import Alert from .common import Notification from .device import Device from .hidpp10_constants import Registers if typing.TYPE_CHECKING: from logitech_receiver import common logger = logging.getLogger(__name__) _hidpp10 = hidpp10.Hidpp10() _IR = hidpp10_constants.INFO_SUBREGISTERS class LowLevelInterface(Protocol): def open_path(self, path): ... def find_paired_node_wpid(self, receiver_path: str, index: int): ... def ping(self, handle, number, long_message=False): ... def request(self, handle, devnumber, request_id, *params, **kwargs): ... def close(self, handle): ... @dataclass class Pairing: """Information about the current or most recent pairing""" lock_open: bool = False discovering: bool = False counter: Optional[int] = None device_address: Optional[bytes] = None device_authentication: Optional[int] = None device_kind: Optional[int] = None device_name: Optional[str] = None device_passkey: Optional[str] = None new_device: Optional[Device] = None error: Optional[any] = None class Receiver: """A generic Receiver instance, mostly implementing the interface used on Unifying, Nano, and LightSpeed receivers" The paired devices are available through the sequence interface. """ read_register: Callable = hidpp10.read_register write_register: Callable = hidpp10.write_register number = 0xFF kind = None def __init__( self, low_level: LowLevelInterface, receiver_kind, product_info, handle, path, product_id, setting_callback=None, ): assert handle self.low_level = low_level self.isDevice = False # some devices act as receiver so we need a property to distinguish them self.handle = handle self.path = path self.product_id = product_id self.setting_callback = setting_callback # for changes to settings self.status_callback = None # for changes to other potentially visible aspects self.receiver_kind = receiver_kind self.serial = None self.max_devices = None self._firmware = None self._remaining_pairings = None self._devices = {} self.name = product_info.get("name", "Receiver") self.may_unpair = product_info.get("may_unpair", False) self.re_pairs = product_info.get("re_pairs", False) self.notification_flags = None self.pairing = Pairing() self.initialize(product_info) hidpp10.set_configuration_pending_flags(self, 0xFF) def initialize(self, product_info: dict): # read the receiver information subregister, so we can find out max_devices serial_reply = self.read_register(Registers.RECEIVER_INFO, _IR.receiver_information) if serial_reply: self.serial = serial_reply[1:5].hex().upper() self.max_devices = serial_reply[6] if self.max_devices <= 0 or self.max_devices > 6: self.max_devices = product_info.get("max_devices", 1) else: # handle receivers that don't have a serial number specially (i.e., c534) self.serial = None self.max_devices = product_info.get("max_devices", 1) def close(self): handle, self.handle = self.handle, None for _n, d in self._devices.items(): if d: d.close() self._devices.clear() return handle and self.low_level.close(handle) def __del__(self): self.close() def changed(self, alert=Alert.NOTIFICATION, reason=None): """The status of the device had changed, so invoke the status callback""" if self.status_callback is not None: self.status_callback(self, alert=alert, reason=reason) @property def firmware(self) -> tuple[common.FirmwareInfo]: if self._firmware is None and self.handle: self._firmware = _hidpp10.get_firmware(self) return self._firmware # how many pairings remain (None for unknown, -1 for unlimited) def remaining_pairings(self, cache=True): if self._remaining_pairings is None or not cache: ps = self.read_register(Registers.RECEIVER_CONNECTION) if ps is not None: ps = ord(ps[2:3]) self._remaining_pairings = ps - 5 if ps >= 5 else -1 return self._remaining_pairings def enable_connection_notifications(self, enable=True): """Enable or disable device (dis)connection notifications on this receiver.""" if not self.handle: return False if enable: set_flag_bits = hidpp10_constants.NOTIFICATION_FLAG.wireless | hidpp10_constants.NOTIFICATION_FLAG.software_present else: set_flag_bits = 0 ok = _hidpp10.set_notification_flags(self, set_flag_bits) if ok is None: logger.warning("%s: failed to %s receiver notifications", self, "enable" if enable else "disable") return None flag_bits = _hidpp10.get_notification_flags(self) flag_names = None if flag_bits is None else tuple(hidpp10_constants.NOTIFICATION_FLAG.flag_names(flag_bits)) if logger.isEnabledFor(logging.INFO): logger.info("%s: receiver notifications %s => %s", self, "enabled" if enable else "disabled", flag_names) return flag_bits def device_codename(self, n): codename = self.read_register(Registers.RECEIVER_INFO, _IR.device_name + n - 1) if codename: codename = codename[2 : 2 + ord(codename[1:2])] return codename.decode("ascii") def notify_devices(self): """Scan all devices.""" if self.handle: if not self.write_register(Registers.RECEIVER_CONNECTION, 0x02): logger.warning("%s: failed to trigger device link notifications", self) def notification_information(self, number, notification): """Extract information from unifying-style notification""" assert notification.address != 0x02 online = not bool(notification.data[0] & 0x40) encrypted = bool(notification.data[0] & 0x20) or notification.address == 0x10 kind = hidpp10_constants.DEVICE_KIND[notification.data[0] & 0x0F] wpid = (notification.data[2:3] + notification.data[1:2]).hex().upper() return online, encrypted, wpid, kind def device_pairing_information(self, n: int) -> dict: """Return information from pairing registers (and elsewhere when necessary)""" polling_rate = "" serial = None power_switch = "(unknown)" pair_info = self.read_register(Registers.RECEIVER_INFO, _IR.pairing_information + n - 1) if pair_info: # a receiver that uses Unifying-style pairing registers wpid = pair_info[3:5].hex().upper() kind = hidpp10_constants.DEVICE_KIND[pair_info[7] & 0x0F] polling_rate = str(pair_info[2]) + "ms" elif not self.receiver_kind == "unifying": # may be an old Nano receiver device_info = self.read_register(Registers.RECEIVER_INFO, 0x04) # undocumented if device_info: logger.warning("using undocumented register for device wpid") wpid = device_info[3:5].hex().upper() kind = hidpp10_constants.DEVICE_KIND[0x00] # unknown kind else: raise exceptions.NoSuchDevice(number=n, receiver=self, error="read pairing information - non-unifying") else: raise exceptions.NoSuchDevice(number=n, receiver=self, error="read pairing information") pair_info = self.read_register(Registers.RECEIVER_INFO, _IR.extended_pairing_information + n - 1) if pair_info: power_switch = hidpp10_constants.POWER_SWITCH_LOCATION[pair_info[9] & 0x0F] serial = pair_info[1:5].hex().upper() else: # some Nano receivers? pair_info = self.read_register(0x2D5) # undocumented and questionable if pair_info: logger.warning("using undocumented register for device serial number") serial = pair_info[1:5].hex().upper() return {"wpid": wpid, "kind": kind, "polling": polling_rate, "serial": serial, "power_switch": power_switch} def register_new_device(self, number, notification=None): if self._devices.get(number) is not None: raise IndexError(f"{self}: device number {int(number)} already registered") assert notification is None or notification.devnumber == number assert notification is None or notification.sub_id == Notification.DJ_PAIRING try: time.sleep(0.05) # let receiver settle info = self.device_pairing_information(number) if notification is not None: online, _e, nwpid, nkind = self.notification_information(number, notification) if info["wpid"] is None: info["wpid"] = nwpid elif nwpid is not None and info["wpid"] != nwpid: logger.warning("mismatch on device WPID %s %s", info["wpid"], nwpid) if info["kind"] is None: info["kind"] = nkind elif nkind is not None and info["kind"] != nkind: logger.warning("mismatch on device kind %s %s", info["kind"], nkind) else: online = True dev = Device(self.low_level, self, number, online, pairing_info=info, setting_callback=self.setting_callback) if logger.isEnabledFor(logging.INFO): logger.info("%s: found new device %d (%s)", self, number, dev.wpid) self._devices[number] = dev return dev except exceptions.NoSuchDevice as e: logger.warning("register new device failed for %s device %d error %s", e.receiver, e.number, e.error) logger.warning("%s: looked for device %d, not found", self, number) self._devices[number] = None def set_lock(self, lock_closed=True, device=0, timeout=0): if self.handle: action = 0x02 if lock_closed else 0x01 reply = self.write_register(Registers.RECEIVER_PAIRING, action, device, timeout) if reply: return True logger.warning("%s: failed to %s the receiver lock", self, "close" if lock_closed else "open") def count(self): count = self.read_register(Registers.RECEIVER_CONNECTION) return 0 if count is None else ord(count[1:2]) def request(self, request_id, *params): if bool(self): return self.low_level.request(self.handle, 0xFF, request_id, *params) def reset_pairing(self): self.pairing = Pairing() def __iter__(self): connected_devices = self.count() found_devices = 0 for number in range(1, 8): # some receivers have devices past their max # devices if found_devices >= connected_devices: return if number in self._devices: dev = self._devices[number] else: dev = self.__getitem__(number) if dev is not None: found_devices += 1 yield dev def __getitem__(self, key): if not bool(self): return None dev = self._devices.get(key) if dev is not None: return dev if not isinstance(key, int): raise TypeError("key must be an integer") if key < 1 or key > 15: # some receivers have devices past their max # devices raise IndexError(key) return self.register_new_device(key) def __delitem__(self, key): self._unpair_device(key, False) def _unpair_device(self, key, force=False): key = int(key) if self._devices.get(key) is None: raise IndexError(key) dev = self._devices[key] if not dev: if key in self._devices: del self._devices[key] return if self.re_pairs and not force: # invalidate the device, but these receivers don't unpair per se dev.online = False dev.wpid = None if key in self._devices: del self._devices[key] logger.warning("%s removed device %s", self, dev) else: reply = self._unpair_device_per_receiver(key) if reply: # invalidate the device dev.online = False dev.wpid = None if key in self._devices: del self._devices[key] if logger.isEnabledFor(logging.INFO): logger.info("%s unpaired device %s", self, dev) else: logger.error("%s failed to unpair device %s", self, dev) raise Exception(f"failed to unpair device {dev.name}: {key}") def _unpair_device_per_receiver(self, key): """Receiver specific unpairing.""" return self.write_register(Registers.RECEIVER_PAIRING, 0x03, key) def __len__(self): return len([d for d in self._devices.values() if d is not None]) def __contains__(self, dev): if isinstance(dev, int): return self._devices.get(dev) is not None return self.__contains__(dev.number) def __eq__(self, other): return other is not None and self.kind == other.kind and self.path == other.path def __ne__(self, other): return other is None or self.kind != other.kind or self.path != other.path def __hash__(self): return self.path.__hash__() def status_string(self): count = len(self) return ( _("No paired devices.") if count == 0 else ngettext("%(count)s paired device.", "%(count)s paired devices.", count) % {"count": count} ) def __str__(self): return "<%s(%s,%s%s)>" % ( self.name.replace(" ", ""), self.path, "" if isinstance(self.handle, int) else "T", self.handle, ) __repr__ = __str__ __bool__ = __nonzero__ = lambda self: self.handle is not None class BoltReceiver(Receiver): """Bolt receivers use a different pairing prototol and have different pairing registers""" def __init__(self, receiver_kind, product_info, handle, path, product_id, setting_callback=None): super().__init__(receiver_kind, product_info, handle, path, product_id, setting_callback) def initialize(self, product_info: dict): serial_reply = self.read_register(Registers.BOLT_UNIQUE_ID) self.serial = serial_reply.hex().upper() self.max_devices = product_info.get("max_devices", 1) def device_codename(self, n): codename = self.read_register(Registers.RECEIVER_INFO, _IR.bolt_device_name + n, 0x01) if codename: codename = codename[3 : 3 + min(14, ord(codename[2:3]))] return codename.decode("ascii") def device_pairing_information(self, n: int) -> dict: pair_info = self.read_register(Registers.RECEIVER_INFO, _IR.bolt_pairing_information + n) if pair_info: wpid = (pair_info[3:4] + pair_info[2:3]).hex().upper() kind = hidpp10_constants.DEVICE_KIND[pair_info[1] & 0x0F] serial = pair_info[4:8].hex().upper() return {"wpid": wpid, "kind": kind, "polling": None, "serial": serial, "power_switch": "(unknown)"} else: raise exceptions.NoSuchDevice(number=n, receiver=self, error="can't read Bolt pairing register") def discover(self, cancel=False, timeout=30): """Discover Logitech Bolt devices.""" if self.handle: action = 0x02 if cancel else 0x01 reply = self.write_register(Registers.BOLT_DEVICE_DISCOVERY, timeout, action) if reply: return True logger.warning("%s: failed to %s device discovery", self, "cancel" if cancel else "start") def pair_device(self, pair=True, slot=0, address=b"\0\0\0\0\0\0", authentication=0x00, entropy=20): """Pair a Bolt device.""" if self.handle: action = 0x01 if pair is True else 0x03 if pair is False else 0x02 reply = self.write_register(Registers.BOLT_PAIRING, action, slot, address, authentication, entropy) if reply: return True logger.warning("%s: failed to %s device %s", self, "pair" if pair else "unpair", address) def _unpair_device_per_receiver(self, key): """Receiver specific unpairing.""" return self.write_register(Registers.BOLT_PAIRING, 0x03, key) class UnifyingReceiver(Receiver): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class NanoReceiver(Receiver): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class LightSpeedReceiver(Receiver): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Ex100Receiver(Receiver): """A very old style receiver, somewhat different from newer receivers""" def __init__(self, receiver_kind, product_info, handle, path, product_id, setting_callback=None): super().__init__(receiver_kind, product_info, handle, path, product_id, setting_callback) def initialize(self, product_info: dict): self.serial = None self.max_devices = product_info.get("max_devices", 1) def notification_information(self, number, notification): """Extract information from 27Mz-style notification and device index""" assert notification.address == 0x02 online = True encrypted = bool(notification.data[0] & 0x80) kind = hidpp10_constants.DEVICE_KIND[_get_kind_from_index(self, number)] wpid = "00" + notification.data[2:3].hex().upper() return online, encrypted, wpid, kind def device_pairing_information(self, number: int) -> dict: # extract WPID from udev path wpid = self.low_level.find_paired_node_wpid(self.path, number) if not wpid: logger.error("Unable to get wpid from udev for device %d of %s", number, self) raise exceptions.NoSuchDevice(number=number, receiver=self, error="Not present 27Mhz device") kind = hidpp10_constants.DEVICE_KIND[_get_kind_from_index(self, number)] return {"wpid": wpid, "kind": kind, "polling": "", "serial": None, "power_switch": "(unknown)"} def _get_kind_from_index(receiver, index): """Get device kind from 27Mhz device index""" # From drivers/hid/hid-logitech-dj.c if index == 1: # mouse kind = 2 elif index == 2: # mouse kind = 2 elif index == 3: # keyboard kind = 1 elif index == 4: # numpad kind = 3 else: # unknown device number on 27Mhz receiver logger.error("failed to calculate device kind for device %d of %s", index, receiver) raise exceptions.NoSuchDevice(number=index, receiver=receiver, error="Unknown 27Mhz device number") return kind receiver_class_mapping = { "bolt": BoltReceiver, "unifying": UnifyingReceiver, "lightspeed": LightSpeedReceiver, "nano": NanoReceiver, "27Mhz": Ex100Receiver, } def create_receiver(low_level: LowLevelInterface, device_info, setting_callback=None) -> Optional[Receiver]: """Opens a Logitech Receiver found attached to the machine, by Linux device path.""" try: handle = low_level.open_path(device_info.path) if handle: usb_id = device_info.product_id if isinstance(usb_id, str): usb_id = int(usb_id, 16) try: product_info = low_level.product_information(usb_id) except ValueError: product_info = {} kind = product_info.get("receiver_kind", "unknown") rclass = receiver_class_mapping.get(kind, Receiver) return rclass( low_level, kind, product_info, handle, device_info.path, device_info.product_id, setting_callback, ) except OSError as e: logger.exception("open %s", device_info) if e.errno == errno.EACCES: raise except Exception: logger.exception("open %s", device_info)
21,796
Python
.py
459
38.174292
127
0.628354
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,454
diversion.py
pwr-Solaar_Solaar/lib/logitech_receiver/diversion.py
## Copyright (C) 2020 Peter Patel-Schneider ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from __future__ import annotations import ctypes import logging import math import numbers import os import platform import socket import struct import subprocess import sys import time import typing from typing import Any from typing import Dict from typing import Tuple import gi import psutil import yaml from keysyms import keysymdef # There is no evdev on macOS or Windows. Diversion will not work without # it but other Solaar functionality is available. if platform.system() in ("Darwin", "Windows"): evdev = None else: import evdev from .common import NamedInt from .hidpp20 import SupportedFeature from .special_keys import CONTROL gi.require_version("Gdk", "3.0") # isort:skip from gi.repository import Gdk, GLib # NOQA: E402 # isort:skip if typing.TYPE_CHECKING: from .base import HIDPPNotification logger = logging.getLogger(__name__) # # See docs/rules.md for documentation # # Several capabilities of rules depend on aspects of GDK, X11, or XKB # As the Solaar GUI uses GTK, Glib and GDK are always available and are obtained from gi.repository # # Process condition depends on X11 from python-xlib, and is probably not possible at all in Wayland # MouseProcess condition depends on X11 from python-xlib, and is probably not possible at all in Wayland # Modifiers condition depends only on GDK # KeyPress action determines whether a keysym is a currently-down modifier using get_modifier_mapping from python-xlib; # under Wayland no modifier keys are considered down so all modifier keys are pressed, potentially leading to problems # KeyPress action translates key names to keysysms using the local file described for GUI keyname determination # KeyPress action gets the current keyboard group using XkbGetState from libX11.so using ctypes definitions # under Wayland the keyboard group is None resulting in using the first keyboard group # KeyPress action translates keysyms to keycodes using the GDK keymap # KeyPress, MouseScroll, and MouseClick actions use XTest (under X11) or uinput. # For uinput to work the user must have write access for /dev/uinput. # To get this access run sudo setfacl -m u:${user}:rw /dev/uinput # # Rule GUI keyname determination uses a local file generated # from http://cgit.freedesktop.org/xorg/proto/x11proto/plain/keysymdef.h # and http://cgit.freedesktop.org/xorg/proto/x11proto/plain/XF86keysym.h # because there does not seem to be a non-X11 file for this set of key names # Setting up is complex because there are several systems that each provide partial facilities: # GDK - always available (when running with a window system) but only provides access to keymap # X11 - provides access to active process and process with window under mouse and current modifier keys # Xtest extension to X11 - provides input simulation, partly works under Wayland # Wayland - provides input simulation XK_KEYS: Dict[str, int] = keysymdef.key_symbols # Event codes - can't use Xlib.X codes because Xlib might not be available _KEY_RELEASE = 0 _KEY_PRESS = 1 _BUTTON_RELEASE = 2 _BUTTON_PRESS = 3 CLICK, DEPRESS, RELEASE = "click", "depress", "release" gdisplay = Gdk.Display.get_default() # can be None if Solaar is run without a full window system gkeymap = Gdk.Keymap.get_for_display(gdisplay) if gdisplay else None if logger.isEnabledFor(logging.INFO): logger.info("GDK Keymap %sset up", "" if gkeymap else "not ") wayland = os.getenv("WAYLAND_DISPLAY") # is this Wayland? if wayland: logger.warning( "rules cannot access modifier keys in Wayland, " "accessing process only works on GNOME with Solaar Gnome extension installed" ) try: import Xlib _x11 = None # X11 might be available except Exception: _x11 = False # X11 is not available # Globals xtest_available = True # Xtest might be available xdisplay = None Xkbdisplay = None # xkb might be available X11Lib = None modifier_keycodes = [] XkbUseCoreKbd = 0x100 NET_ACTIVE_WINDOW = None NET_WM_PID = None WM_CLASS = None udevice = None key_down = None key_up = None keys_down = [] g_keys_down = 0 m_keys_down = 0 mr_key_down = False thumb_wheel_displacement = 0 _dbus_interface = None class XkbDisplay(ctypes.Structure): """opaque struct""" class XkbStateRec(ctypes.Structure): _fields_ = [ ("group", ctypes.c_ubyte), ("locked_group", ctypes.c_ubyte), ("base_group", ctypes.c_ushort), ("latched_group", ctypes.c_ushort), ("mods", ctypes.c_ubyte), ("base_mods", ctypes.c_ubyte), ("latched_mods", ctypes.c_ubyte), ("locked_mods", ctypes.c_ubyte), ("compat_state", ctypes.c_ubyte), ("grab_mods", ctypes.c_ubyte), ("compat_grab_mods", ctypes.c_ubyte), ("lookup_mods", ctypes.c_ubyte), ("compat_lookup_mods", ctypes.c_ubyte), ("ptr_buttons", ctypes.c_ushort), ] # something strange is happening here but it is not being used def x11_setup(): global _x11, xdisplay, modifier_keycodes, NET_ACTIVE_WINDOW, NET_WM_PID, WM_CLASS, xtest_available if _x11 is not None: return _x11 try: from Xlib.display import Display xdisplay = Display() modifier_keycodes = xdisplay.get_modifier_mapping() # there should be a way to do this in Gdk NET_ACTIVE_WINDOW = xdisplay.intern_atom("_NET_ACTIVE_WINDOW") NET_WM_PID = xdisplay.intern_atom("_NET_WM_PID") WM_CLASS = xdisplay.intern_atom("WM_CLASS") _x11 = True # X11 available if logger.isEnabledFor(logging.INFO): logger.info("X11 library loaded and display set up") except Exception: logger.warning("X11 not available - some rule capabilities inoperable", exc_info=sys.exc_info()) _x11 = False xtest_available = False return _x11 def gnome_dbus_interface_setup(): global _dbus_interface if _dbus_interface is not None: return _dbus_interface try: import dbus bus = dbus.SessionBus() remote_object = bus.get_object("org.gnome.Shell", "/io/github/pwr_solaar/solaar") _dbus_interface = dbus.Interface(remote_object, "io.github.pwr_solaar.solaar") except dbus.exceptions.DBusException: logger.warning( "Solaar Gnome extension not installed - some rule capabilities inoperable", exc_info=sys.exc_info(), ) _dbus_interface = False return _dbus_interface def xkb_setup(): global X11Lib, Xkbdisplay if Xkbdisplay is not None: return Xkbdisplay try: # set up to get keyboard state using ctypes interface to libx11 X11Lib = ctypes.cdll.LoadLibrary("libX11.so") X11Lib.XOpenDisplay.restype = ctypes.POINTER(XkbDisplay) X11Lib.XkbGetState.argtypes = [ctypes.POINTER(XkbDisplay), ctypes.c_uint, ctypes.POINTER(XkbStateRec)] Xkbdisplay = X11Lib.XOpenDisplay(None) if logger.isEnabledFor(logging.INFO): logger.info("XKB display set up") except Exception: logger.warning("XKB display not available - rules cannot access keyboard group", exc_info=sys.exc_info()) Xkbdisplay = False return Xkbdisplay if evdev: buttons = { "unknown": (None, None), "left": (1, evdev.ecodes.ecodes["BTN_LEFT"]), "middle": (2, evdev.ecodes.ecodes["BTN_MIDDLE"]), "right": (3, evdev.ecodes.ecodes["BTN_RIGHT"]), "scroll_up": (4, evdev.ecodes.ecodes["BTN_4"]), "scroll_down": (5, evdev.ecodes.ecodes["BTN_5"]), "scroll_left": (6, evdev.ecodes.ecodes["BTN_6"]), "scroll_right": (7, evdev.ecodes.ecodes["BTN_7"]), "button8": (8, evdev.ecodes.ecodes["BTN_8"]), "button9": (9, evdev.ecodes.ecodes["BTN_9"]), } # uinput capability for keyboard keys, mouse buttons, and scrolling key_events = [c for n, c in evdev.ecodes.ecodes.items() if n.startswith("KEY") and n != "KEY_CNT"] for _, evcode in buttons.values(): if evcode: key_events.append(evcode) devicecap = { evdev.ecodes.EV_KEY: key_events, evdev.ecodes.EV_REL: [evdev.ecodes.REL_WHEEL, evdev.ecodes.REL_HWHEEL], } else: # Just mock these since they won't be useful without evdev anyway buttons = {} key_events = [] devicecap = {} def setup_uinput(): global udevice if udevice is not None: return udevice try: udevice = evdev.uinput.UInput(events=devicecap, name="solaar-keyboard") if logger.isEnabledFor(logging.INFO): logger.info("uinput device set up") return True except Exception as e: logger.warning("cannot create uinput device: %s", e) if wayland: # Wayland can't use xtest so may as well set up uinput now setup_uinput() def kbdgroup(): if xkb_setup(): state = XkbStateRec() X11Lib.XkbGetState(Xkbdisplay, XkbUseCoreKbd, ctypes.pointer(state)) return state.group else: return None def modifier_code(keycode): if wayland or not x11_setup() or keycode == 0: return None for m in range(0, len(modifier_keycodes)): if keycode in modifier_keycodes[m]: return m def signed(bytes_: bytes) -> int: return int.from_bytes(bytes_, "big", signed=True) def xy_direction(_x, _y): # normalize x and y m = math.sqrt((_x * _x) + (_y * _y)) if m == 0: return "noop" x = round(_x / m) y = round(_y / m) if x < 0 and y < 0: return "Mouse Up-left" elif x > 0 > y: return "Mouse Up-right" elif x < 0 < y: return "Mouse Down-left" elif x > 0 and y > 0: return "Mouse Down-right" elif x > 0: return "Mouse Right" elif x < 0: return "Mouse Left" elif y > 0: return "Mouse Down" elif y < 0: return "Mouse Up" else: return "noop" def simulate_xtest(code, event): global xtest_available if x11_setup() and xtest_available: try: event = ( Xlib.X.KeyPress if event == _KEY_PRESS else Xlib.X.KeyRelease if event == _KEY_RELEASE else Xlib.X.ButtonPress if event == _BUTTON_PRESS else Xlib.X.ButtonRelease if event == _BUTTON_RELEASE else None ) Xlib.ext.xtest.fake_input(xdisplay, event, code) xdisplay.sync() if logger.isEnabledFor(logging.DEBUG): logger.debug("xtest simulated input %s %s %s", xdisplay, event, code) return True except Exception as e: xtest_available = False logger.warning("xtest fake input failed: %s", e) def simulate_uinput(what, code, arg): global udevice if setup_uinput(): try: udevice.write(what, code, arg) udevice.syn() if logger.isEnabledFor(logging.DEBUG): logger.debug("uinput simulated input %s %s %s", what, code, arg) return True except Exception as e: udevice = None logger.warning("uinput write failed: %s", e) def simulate_key(code, event): # X11 keycode but Solaar event code if not wayland and simulate_xtest(code, event): return True if simulate_uinput(evdev.ecodes.EV_KEY, code - 8, event): return True logger.warning("no way to simulate key input") def click_xtest(button, count): if isinstance(count, int): for _ in range(count): if not simulate_xtest(button[0], _BUTTON_PRESS): return False if not simulate_xtest(button[0], _BUTTON_RELEASE): return False else: if count != RELEASE: if not simulate_xtest(button[0], _BUTTON_PRESS): return False if count != DEPRESS: if not simulate_xtest(button[0], _BUTTON_RELEASE): return False return True def click_uinput(button, count): if isinstance(count, int): for _ in range(count): if not simulate_uinput(evdev.ecodes.EV_KEY, button[1], 1): return False if not simulate_uinput(evdev.ecodes.EV_KEY, button[1], 0): return False else: if count != RELEASE: if not simulate_uinput(evdev.ecodes.EV_KEY, button[1], 1): return False if count != DEPRESS: if not simulate_uinput(evdev.ecodes.EV_KEY, button[1], 0): return False return True def click(button, count): if not wayland and click_xtest(button, count): return True if click_uinput(button, count): return True logger.warning("no way to simulate mouse click") return False def simulate_scroll(dx, dy): if not wayland and xtest_available: success = True if dx: success = click_xtest(buttons["scroll_right" if dx > 0 else "scroll_left"], count=abs(dx)) if dy and success: success = click_xtest(buttons["scroll_up" if dy > 0 else "scroll_down"], count=abs(dy)) if success: return True if setup_uinput(): success = True if dx: success = simulate_uinput(evdev.ecodes.EV_REL, evdev.ecodes.REL_HWHEEL, dx) if dy and success: success = simulate_uinput(evdev.ecodes.EV_REL, evdev.ecodes.REL_WHEEL, dy) if success: return True logger.warning("no way to simulate scrolling") def thumb_wheel_up(f, r, d, a): global thumb_wheel_displacement if f != SupportedFeature.THUMB_WHEEL or r != 0: return False if a is None: return signed(d[0:2]) < 0 and signed(d[0:2]) elif thumb_wheel_displacement <= -a: thumb_wheel_displacement += a return 1 else: return False def thumb_wheel_down(f, r, d, a): global thumb_wheel_displacement if f != SupportedFeature.THUMB_WHEEL or r != 0: return False if a is None: return signed(d[0:2]) > 0 and signed(d[0:2]) elif thumb_wheel_displacement >= a: thumb_wheel_displacement -= a return 1 else: return False def charging(f, r, d, _a): if ( (f == SupportedFeature.BATTERY_STATUS and r == 0 and 1 <= d[2] <= 4) or (f == SupportedFeature.BATTERY_VOLTAGE and r == 0 and d[2] & (1 << 7)) or (f == SupportedFeature.UNIFIED_BATTERY and r == 0 and 1 <= d[2] <= 3) ): return 1 else: return False TESTS = { "crown_right": [lambda f, r, d, a: f == SupportedFeature.CROWN and r == 0 and d[1] < 128 and d[1], False], "crown_left": [lambda f, r, d, a: f == SupportedFeature.CROWN and r == 0 and d[1] >= 128 and 256 - d[1], False], "crown_right_ratchet": [lambda f, r, d, a: f == SupportedFeature.CROWN and r == 0 and d[2] < 128 and d[2], False], "crown_left_ratchet": [lambda f, r, d, a: f == SupportedFeature.CROWN and r == 0 and d[2] >= 128 and 256 - d[2], False], "crown_tap": [lambda f, r, d, a: f == SupportedFeature.CROWN and r == 0 and d[5] == 0x01 and d[5], False], "crown_start_press": [lambda f, r, d, a: f == SupportedFeature.CROWN and r == 0 and d[6] == 0x01 and d[6], False], "crown_end_press": [lambda f, r, d, a: f == SupportedFeature.CROWN and r == 0 and d[6] == 0x05 and d[6], False], "crown_pressed": [lambda f, r, d, a: f == SupportedFeature.CROWN and r == 0 and 0x01 <= d[6] <= 0x04 and d[6], False], "thumb_wheel_up": [thumb_wheel_up, True], "thumb_wheel_down": [thumb_wheel_down, True], "lowres_wheel_up": [ lambda f, r, d, a: f == SupportedFeature.LOWRES_WHEEL and r == 0 and signed(d[0:1]) > 0 and signed(d[0:1]), False, ], "lowres_wheel_down": [ lambda f, r, d, a: f == SupportedFeature.LOWRES_WHEEL and r == 0 and signed(d[0:1]) < 0 and signed(d[0:1]), False, ], "hires_wheel_up": [ lambda f, r, d, a: f == SupportedFeature.HIRES_WHEEL and r == 0 and signed(d[1:3]) > 0 and signed(d[1:3]), False, ], "hires_wheel_down": [ lambda f, r, d, a: f == SupportedFeature.HIRES_WHEEL and r == 0 and signed(d[1:3]) < 0 and signed(d[1:3]), False, ], "charging": [charging, False], "False": [lambda f, r, d, a: False, False], "True": [lambda f, r, d, a: True, False], } MOUSE_GESTURE_TESTS = { "mouse-down": ["Mouse Down"], "mouse-up": ["Mouse Up"], "mouse-left": ["Mouse Left"], "mouse-right": ["Mouse Right"], "mouse-noop": [], } # COMPONENTS = {} class RuleComponent: def compile(self, c): if isinstance(c, RuleComponent): return c elif isinstance(c, dict) and len(c) == 1: k, v = next(iter(c.items())) if k in COMPONENTS: return COMPONENTS[k](v) logger.warning("illegal component in rule: %s", c) return Condition() def _evaluate(components, feature, notification: HIDPPNotification, device, result) -> Any: res = True for component in components: res = component.evaluate(feature, notification, device, result) if not isinstance(component, Action) and res is None: return None if isinstance(component, Condition) and not res: return res return res class Rule(RuleComponent): def __init__(self, args, source=None, warn=True): self.components = [self.compile(a) for a in args] self.source = source def __str__(self): source = "(" + self.source + ")" if self.source else "" return f"Rule{source}[{', '.join([c.__str__() for c in self.components])}]" def evaluate(self, feature, notification: HIDPPNotification, device, last_result): if logger.isEnabledFor(logging.DEBUG): logger.debug("evaluate rule: %s", self) return _evaluate(self.components, feature, notification, device, True) def once(self, feature, notification: HIDPPNotification, device, last_result): self.evaluate(feature, notification, device, last_result) return False def data(self): return {"Rule": [c.data() for c in self.components]} class Condition(RuleComponent): def __init__(self, *args): pass def __str__(self): return "CONDITION" def evaluate(self, feature, notification: HIDPPNotification, device, last_result): if logger.isEnabledFor(logging.DEBUG): logger.debug("evaluate condition: %s", self) return False class Not(Condition): def __init__(self, op, warn=True): if isinstance(op, list) and len(op) == 1: op = op[0] self.op = op self.component = self.compile(op) def __str__(self): return "Not: " + str(self.component) def evaluate(self, feature, notification: HIDPPNotification, device, last_result): if logger.isEnabledFor(logging.DEBUG): logger.debug("evaluate condition: %s", self) result = self.component.evaluate(feature, notification, device, last_result) return None if result is None else not result def data(self): return {"Not": self.component.data()} class Or(Condition): def __init__(self, args, warn=True): self.components = [self.compile(a) for a in args] def __str__(self): return "Or: [" + ", ".join(str(c) for c in self.components) + "]" def evaluate(self, feature, notification: HIDPPNotification, device, last_result): if logger.isEnabledFor(logging.DEBUG): logger.debug("evaluate condition: %s", self) result = False for component in self.components: result = component.evaluate(feature, notification, device, last_result) if not isinstance(component, Action) and result is None: return None if isinstance(component, Condition) and result: return result return result def data(self): return {"Or": [c.data() for c in self.components]} class And(Condition): def __init__(self, args, warn=True): self.components = [self.compile(a) for a in args] def __str__(self): return "And: [" + ", ".join(str(c) for c in self.components) + "]" def evaluate(self, feature, notification: HIDPPNotification, device, last_result): if logger.isEnabledFor(logging.DEBUG): logger.debug("evaluate condition: %s", self) return _evaluate(self.components, feature, notification, device, last_result) def data(self): return {"And": [c.data() for c in self.components]} def x11_focus_prog(): if not x11_setup(): return None pid = wm_class = None window = xdisplay.get_input_focus().focus while window: pid = window.get_full_property(NET_WM_PID, 0) wm_class = window.get_wm_class() if wm_class and pid: break window = window.query_tree().parent try: name = psutil.Process(pid.value[0]).name() if pid else "" except Exception: name = "" return (wm_class[0], wm_class[1], name) if wm_class else (name,) def x11_pointer_prog(): if not x11_setup(): return None pid = wm_class = None window = xdisplay.screen().root.query_pointer().child for child in reversed(window.query_tree().children): pid = child.get_full_property(NET_WM_PID, 0) wm_class = child.get_wm_class() if wm_class: break name = psutil.Process(pid.value[0]).name() if pid else "" return (wm_class[0], wm_class[1], name) if wm_class else (name,) def gnome_dbus_focus_prog(): if not gnome_dbus_interface_setup(): return None wm_class = _dbus_interface.ActiveWindow() return (wm_class,) if wm_class else None def gnome_dbus_pointer_prog(): if not gnome_dbus_interface_setup(): return None wm_class = _dbus_interface.PointerOverWindow() return (wm_class,) if wm_class else None class Process(Condition): def __init__(self, process, warn=True): self.process = process if (not wayland and not x11_setup()) or (wayland and not gnome_dbus_interface_setup()): if warn: logger.warning( "rules can only access active process in X11 or in Wayland under GNOME with Solaar Gnome " "extension - %s", self, ) if not isinstance(process, str): if warn: logger.warning("rule Process argument not a string: %s", process) self.process = str(process) def __str__(self): return "Process: " + str(self.process) def evaluate(self, feature, notification: HIDPPNotification, device, last_result): if logger.isEnabledFor(logging.DEBUG): logger.debug("evaluate condition: %s", self) if not isinstance(self.process, str): return False focus = x11_focus_prog() if not wayland else gnome_dbus_focus_prog() result = any(bool(s and s.startswith(self.process)) for s in focus) if focus else None return result def data(self): return {"Process": str(self.process)} class MouseProcess(Condition): def __init__(self, process, warn=True): self.process = process if (not wayland and not x11_setup()) or (wayland and not gnome_dbus_interface_setup()): if warn: logger.warning( "rules cannot access active mouse process " "in X11 or in Wayland under GNOME with Solaar Extension for GNOME - %s", self, ) if not isinstance(process, str): if warn: logger.warning("rule MouseProcess argument not a string: %s", process) self.process = str(process) def __str__(self): return "MouseProcess: " + str(self.process) def evaluate(self, feature, notification: HIDPPNotification, device, last_result): if logger.isEnabledFor(logging.DEBUG): logger.debug("evaluate condition: %s", self) if not isinstance(self.process, str): return False pointer_focus = x11_pointer_prog() if not wayland else gnome_dbus_pointer_prog() result = any(bool(s and s.startswith(self.process)) for s in pointer_focus) if pointer_focus else None return result def data(self): return {"MouseProcess": str(self.process)} class Feature(Condition): def __init__(self, feature: str, warn: bool = True): try: self.feature = SupportedFeature[feature] except KeyError: self.feature = None if warn: logger.warning("rule Feature argument not name of a feature: %s", feature) def __str__(self): return "Feature: " + str(self.feature) def evaluate(self, feature, notification: HIDPPNotification, device, last_result): if logger.isEnabledFor(logging.DEBUG): logger.debug("evaluate condition: %s", self) return feature == self.feature def data(self): return {"Feature": str(self.feature)} class Report(Condition): def __init__(self, report, warn=True): if not (isinstance(report, int)): if warn: logger.warning("rule Report argument not an integer: %s", report) self.report = -1 else: self.report = report def __str__(self): return "Report: " + str(self.report) def evaluate(self, report, notification: HIDPPNotification, device, last_result): if logger.isEnabledFor(logging.DEBUG): logger.debug("evaluate condition: %s", self) return (notification.address >> 4) == self.report def data(self): return {"Report": self.report} # Setting(device, setting, [key], value...) class Setting(Condition): def __init__(self, args, warn=True): if not (isinstance(args, list) and len(args) > 2): if warn: logger.warning("rule Setting argument not list with minimum length 3: %s", args) self.args = [] else: self.args = args def __str__(self): return "Setting: " + " ".join([str(a) for a in self.args]) def evaluate(self, report, notification: HIDPPNotification, device, last_result): if logger.isEnabledFor(logging.DEBUG): logger.debug("evaluate condition: %s", self) if len(self.args) < 3: return None dev = device.find(self.args[0]) if self.args[0] is not None else device if dev is None: logger.warning("Setting condition: device %s is not known", self.args[0]) return False setting = next((s for s in dev.settings if s.name == self.args[1]), None) if setting is None: logger.warning("Setting condition: setting %s is not the name of a setting for %s", self.args[1], dev.name) return None # should the value argument be checked to be sure it is acceptable?? needs to be careful about boolean toggle # TODO add compare methods for more validators try: result = setting.compare(self.args[2:], setting.read()) except Exception as e: logger.warning("Setting condition: error when checking setting %s: %s", self.args, e) result = False return result def data(self): return {"Setting": self.args[:]} MODIFIERS = { "Shift": int(Gdk.ModifierType.SHIFT_MASK), "Control": int(Gdk.ModifierType.CONTROL_MASK), "Alt": int(Gdk.ModifierType.MOD1_MASK), "Super": int(Gdk.ModifierType.MOD4_MASK), } MODIFIER_MASK = MODIFIERS["Shift"] + MODIFIERS["Control"] + MODIFIERS["Alt"] + MODIFIERS["Super"] class Modifiers(Condition): def __init__(self, modifiers, warn=True): modifiers = [modifiers] if isinstance(modifiers, str) else modifiers self.desired = 0 self.modifiers = [] for k in modifiers: if k in MODIFIERS: self.desired += MODIFIERS.get(k, 0) self.modifiers.append(k) else: if warn: logger.warning("unknown rule Modifier value: %s", k) def __str__(self): return "Modifiers: " + str(self.desired) def evaluate(self, feature, notification: HIDPPNotification, device, last_result): if logger.isEnabledFor(logging.DEBUG): logger.debug("evaluate condition: %s", self) if gkeymap: current = gkeymap.get_modifier_state() # get the current keyboard modifier return self.desired == (current & MODIFIER_MASK) else: logger.warning("no keymap so cannot determine modifier keys") return False def data(self): return {"Modifiers": [str(m) for m in self.modifiers]} class Key(Condition): DOWN = "pressed" UP = "released" def __init__(self, args, warn=True): default_key = 0 default_action = self.DOWN key, action = None, None if not args or not isinstance(args, (list, str)): if warn: logger.warning(f"rule Key arguments unknown: {args}") key = default_key action = default_action elif isinstance(args, str): logger.debug(f'rule Key assuming action "{default_action}" for "{args}"') key = args action = default_action elif isinstance(args, list): if len(args) == 1: logger.debug(f'rule Key assuming action "{default_action}" for "{args}"') key, action = args[0], default_action elif len(args) >= 2: key, action = args[:2] if isinstance(key, str) and key in CONTROL: self.key = CONTROL[key] elif isinstance(key, str) and key.startswith("unknown:"): logger.info(f"rule Key key name currently unknown: {key}") self.key = CONTROL[int(key[-4:], 16)] else: if warn: logger.warning(f"rule Key key name not name of a Logitech key: {key}") self.key = default_key if isinstance(action, str) and action in (self.DOWN, self.UP): self.action = action else: if warn: logger.warning(f"rule Key action unknown: {action}, assuming {default_action}") self.action = default_action def __str__(self): return f"Key: {str(self.key) if self.key else 'None'} ({self.action})" def evaluate(self, feature, notification: HIDPPNotification, device, last_result): if logger.isEnabledFor(logging.DEBUG): logger.debug("evaluate condition: %s", self) return bool(self.key and self.key == (key_down if self.action == self.DOWN else key_up)) def data(self): return {"Key": [str(self.key), self.action]} class KeyIsDown(Condition): def __init__(self, args, warn=True): default_key = 0 key = None if not args or not isinstance(args, str): if warn: logger.warning(f"rule KeyDown arguments unknown: {args}") key = default_key elif isinstance(args, str): key = args if isinstance(key, str) and key in CONTROL: self.key = CONTROL[key] else: if warn: logger.warning(f"rule Key key name not name of a Logitech key: {key}") self.key = default_key def __str__(self): return f"KeyIsDown: {str(self.key) if self.key else 'None'}" def evaluate(self, feature, notification: HIDPPNotification, device, last_result): if logger.isEnabledFor(logging.DEBUG): logger.debug("evaluate condition: %s", self) return key_is_down(self.key) def data(self): return {"KeyIsDown": str(self.key)} def bit_test(start, end, bits): return lambda f, r, d: int.from_bytes(d[start:end], byteorder="big", signed=True) & bits def range_test(start, end, min, max): def range_test_helper(_f, _r, d): value = int.from_bytes(d[start:end], byteorder="big", signed=True) return min <= value <= max and (value if value else True) return range_test_helper class Test(Condition): def __init__(self, test, warn=True): self.test = "" self.parameter = None if isinstance(test, str): test = [test] if isinstance(test, list) and all(isinstance(t, int) for t in test): if warn: logger.warning("Test rules consisting of numbers are deprecated, converting to a TestBytes condition") self.__class__ = TestBytes self.__init__(test, warn=warn) elif isinstance(test, list): if test[0] in MOUSE_GESTURE_TESTS: if warn: logger.warning("mouse movement test %s deprecated, converting to a MouseGesture", test) self.__class__ = MouseGesture self.__init__(MOUSE_GESTURE_TESTS[0][test], warn=warn) elif test[0] in TESTS: self.test = test[0] self.function = TESTS[test[0]][0] self.parameter = test[1] if len(test) > 1 else None else: if warn: logger.warning("rule Test name not name of a test: %s", test) self.test = "False" self.function = TESTS["False"][0] else: if warn: logger.warning("rule Test argument not valid %s", test) def __str__(self): return "Test: " + str(self.test) def evaluate(self, feature, notification: HIDPPNotification, device, last_result): if logger.isEnabledFor(logging.DEBUG): logger.debug("evaluate condition: %s", self) return self.function(feature, notification.address, notification.data, self.parameter) def data(self): return {"Test": ([self.test, self.parameter] if self.parameter is not None else [self.test])} class TestBytes(Condition): def __init__(self, test, warn=True): self.test = test if ( isinstance(test, list) and 2 < len(test) <= 4 and all(isinstance(t, int) for t in test) and 0 <= test[0] <= 16 and 0 <= test[1] <= 16 and test[0] < test[1] ): self.function = bit_test(*test) if len(test) == 3 else range_test(*test) else: if warn: logger.warning("rule TestBytes argument not valid %s", test) def __str__(self): return "TestBytes: " + str(self.test) def evaluate(self, feature, notification: HIDPPNotification, device, last_result): if logger.isEnabledFor(logging.DEBUG): logger.debug("evaluate condition: %s", self) return self.function(feature, notification.address, notification.data) def data(self): return {"TestBytes": self.test[:]} class MouseGesture(Condition): MOVEMENTS = [ "Mouse Up", "Mouse Down", "Mouse Left", "Mouse Right", "Mouse Up-left", "Mouse Up-right", "Mouse Down-left", "Mouse Down-right", ] def __init__(self, movements, warn=True): if isinstance(movements, str): movements = [movements] for x in movements: if x not in self.MOVEMENTS and x not in CONTROL: if warn: logger.warning("rule Mouse Gesture argument not direction or name of a Logitech key: %s", x) self.movements = movements def __str__(self): return "MouseGesture: " + " ".join(self.movements) def evaluate(self, feature, notification: HIDPPNotification, device, last_result): if logger.isEnabledFor(logging.DEBUG): logger.debug("evaluate condition: %s", self) if feature == SupportedFeature.MOUSE_GESTURE: d = notification.data data = struct.unpack("!" + (int(len(d) / 2) * "h"), d) data_offset = 1 movement_offset = 0 if self.movements and self.movements[0] not in self.MOVEMENTS: # matching against initiating key movement_offset = 1 if self.movements[0] != str(CONTROL[data[0]]): return False for m in self.movements[movement_offset:]: if data_offset >= len(data): return False if data[data_offset] == 0: direction = xy_direction(data[data_offset + 1], data[data_offset + 2]) if m != direction: return False data_offset += 3 elif data[data_offset] == 1: if m != str(CONTROL[data[data_offset + 1]]): return False data_offset += 2 return data_offset == len(data) return False def data(self): return {"MouseGesture": [str(m) for m in self.movements]} class Active(Condition): def __init__(self, devID, warn=True): if not (isinstance(devID, str)): if warn: logger.warning("rule Active argument not a string: %s", devID) self.devID = "" self.devID = devID def __str__(self): return "Active: " + str(self.devID) def evaluate(self, feature, notification: HIDPPNotification, device, last_result): if logger.isEnabledFor(logging.DEBUG): logger.debug("evaluate condition: %s", self) dev = device.find(self.devID) return bool(dev and dev.ping()) def data(self): return {"Active": self.devID} class Device(Condition): def __init__(self, devID, warn=True): if not (isinstance(devID, str)): if warn: logger.warning("rule Device argument not a string: %s", devID) self.devID = "" self.devID = devID def __str__(self): return "Device: " + str(self.devID) def evaluate(self, feature, notification: HIDPPNotification, device, last_result): if logger.isEnabledFor(logging.DEBUG): logger.debug("evaluate condition: %s", self) return device.unitId == self.devID or device.serial == self.devID def data(self): return {"Device": self.devID} class Host(Condition): def __init__(self, host, warn=True): if not (isinstance(host, str)): if warn: logger.warning("rule Host Name argument not a string: %s", host) self.host = "" self.host = host def __str__(self): return "Host: " + str(self.host) def evaluate(self, feature, notification: HIDPPNotification, device, last_result): if logger.isEnabledFor(logging.DEBUG): logger.debug("evaluate condition: %s", self) hostname = socket.getfqdn() return hostname.startswith(self.host) def data(self): return {"Host": self.host} class Action(RuleComponent): def __init__(self, *args): pass def evaluate(self, feature, notification: HIDPPNotification, device, last_result): return None def keysym_to_keycode(keysym, _modifiers) -> Tuple[int, int]: # maybe should take shift into account """Reverse the keycode to keysym mapping. Warning: This is an attempt to reverse the keycode to keysym mappping in XKB. It may not be completely general. """ group = kbdgroup() or 0 keycodes = gkeymap.get_entries_for_keyval(keysym) (keycode, level) = (None, None) for k in keycodes.keys: # mappings that have the correct group if group == k.group and k.keycode < 256 and (level is None or k.level < level): keycode = k.keycode level = k.level if keycode or group == 0: return keycode, level for k in keycodes.keys: # mappings for group 0 where keycode only has group 0 mappings if 0 == k.group and k.keycode < 256 and (level is None or k.level < level): (a, m, vs) = gkeymap.get_entries_for_keycode(k.keycode) if a and all(mk.group == 0 for mk in m): keycode = k.keycode level = k.level return keycode, level class KeyPress(Action): def __init__(self, args, warn=True): self.key_names, self.action = self.regularize_args(args) if not isinstance(self.key_names, list): if warn: logger.warning("rule KeyPress keys not key names %s", self.keys_names) self.key_symbols = [] else: self.key_symbols = [XK_KEYS.get(k, None) for k in self.key_names] if not all(self.key_symbols): if warn: logger.warning("rule KeyPress keys not key names %s", self.key_names) self.key_symbols = [] def regularize_args(self, args): action = CLICK if not isinstance(args, list): args = [args] keys = args if len(args) == 2 and args[1] in [CLICK, DEPRESS, RELEASE]: keys = [args[0]] if isinstance(args[0], str) else args[0] action = args[1] return keys, action def __str__(self): return "KeyPress: " + " ".join(self.key_names) + " " + self.action def needed(self, k, modifiers): code = modifier_code(k) return not (code is not None and modifiers & (1 << code)) def mods(self, level, modifiers, direction): if level == 2 or level == 3: (sk, _) = keysym_to_keycode(XK_KEYS.get("ISO_Level3_Shift", None), modifiers) if sk and self.needed(sk, modifiers): simulate_key(sk, direction) if level == 1 or level == 3: (sk, _) = keysym_to_keycode(XK_KEYS.get("Shift_L", None), modifiers) if sk and self.needed(sk, modifiers): simulate_key(sk, direction) def keyDown(self, keysyms_, modifiers): for k in keysyms_: (keycode, level) = keysym_to_keycode(k, modifiers) if keycode is None: logger.warning("rule KeyPress key symbol not currently available %s", self) elif self.action != CLICK or self.needed(keycode, modifiers): # only check needed when clicking self.mods(level, modifiers, _KEY_PRESS) simulate_key(keycode, _KEY_PRESS) def keyUp(self, keysyms_, modifiers): for k in keysyms_: (keycode, level) = keysym_to_keycode(k, modifiers) if keycode and (self.action != CLICK or self.needed(keycode, modifiers)): # only check needed when clicking simulate_key(keycode, _KEY_RELEASE) self.mods(level, modifiers, _KEY_RELEASE) def evaluate(self, feature, notification: HIDPPNotification, device, last_result): if gkeymap: current = gkeymap.get_modifier_state() if logger.isEnabledFor(logging.INFO): logger.info( "KeyPress action: %s %s, group %s, modifiers %s", self.key_names, self.action, kbdgroup(), current, ) if self.action != RELEASE: self.keyDown(self.key_symbols, current) if self.action != DEPRESS: self.keyUp(reversed(self.key_symbols), current) time.sleep(0.01) else: logger.warning("no keymap so cannot determine which keycode to send") return None def data(self): return {"KeyPress": [[str(k) for k in self.key_names], self.action]} # KeyDown is dangerous as the key can auto-repeat and make your system unusable # class KeyDown(KeyPress): # def evaluate(self, feature, notification: HIDPPNotification, device, last_result): # super().keyDown(self.keys, current_key_modifiers) # class KeyUp(KeyPress): # def evaluate(self, feature, notification: HIDPPNotification, device, last_result): # super().keyUp(self.keys, current_key_modifiers) class MouseScroll(Action): def __init__(self, amounts, warn=True): if len(amounts) == 1 and isinstance(amounts[0], list): amounts = amounts[0] if not (len(amounts) == 2 and all([isinstance(a, numbers.Number) for a in amounts])): if warn: logger.warning("rule MouseScroll argument not two numbers %s", amounts) amounts = [0, 0] self.amounts = amounts def __str__(self): return "MouseScroll: " + " ".join([str(a) for a in self.amounts]) def evaluate(self, feature, notification: HIDPPNotification, device, last_result): amounts = self.amounts if isinstance(last_result, numbers.Number): amounts = [math.floor(last_result * a) for a in self.amounts] if logger.isEnabledFor(logging.INFO): logger.info("MouseScroll action: %s %s %s", self.amounts, last_result, amounts) dx, dy = amounts simulate_scroll(dx, dy) time.sleep(0.01) return None def data(self): return {"MouseScroll": self.amounts[:]} class MouseClick(Action): def __init__(self, args, warn=True): if len(args) == 1 and isinstance(args[0], list): args = args[0] if not isinstance(args, list): args = [args] self.button = str(args[0]) if len(args) >= 0 else None if self.button not in buttons: if warn: logger.warning("rule MouseClick action: button %s not known", self.button) self.button = None count = args[1] if len(args) >= 2 else 1 try: self.count = int(count) except (ValueError, TypeError): if count in [CLICK, DEPRESS, RELEASE]: self.count = count elif warn: logger.warning( "rule MouseClick action: argument %s should be an integer or CLICK, PRESS, or RELEASE", count, ) self.count = 1 def __str__(self): return f"MouseClick: {self.button} ({int(self.count)})" def evaluate(self, feature, notification: HIDPPNotification, device, last_result): if logger.isEnabledFor(logging.INFO): logger.info(f"MouseClick action: {int(self.count)} {self.button}") if self.button and self.count: click(buttons[self.button], self.count) time.sleep(0.01) return None def data(self): return {"MouseClick": [self.button, self.count]} class Set(Action): def __init__(self, args, warn=True): if not (isinstance(args, list) and len(args) > 2): if warn: logger.warning("rule Set argument not list with minimum length 3: %s", args) self.args = [] else: self.args = args def __str__(self): return "Set: " + " ".join([str(a) for a in self.args]) def evaluate(self, feature, notification: HIDPPNotification, device, last_result): if len(self.args) < 3: return None if logger.isEnabledFor(logging.INFO): logger.info("Set action: %s", self.args) dev = device.find(self.args[0]) if self.args[0] is not None else device if dev is None: logger.warning("Set action: device %s is not known", self.args[0]) return None setting = next((s for s in dev.settings if s.name == self.args[1]), None) if setting is None: logger.warning("Set action: setting %s is not the name of a setting for %s", self.args[1], dev.name) return None args = setting.acceptable(self.args[2:], setting.read()) if args is None: logger.warning( "Set Action: invalid args %s for setting %s of %s", self.args[2:], self.args[1], self.args[0], ) return None if len(args) > 1: setting.write_key_value(args[0], args[1]) else: setting.write(args[0]) if device.setting_callback: device.setting_callback(device, type(setting), args) return None def data(self): return {"Set": self.args[:]} class Execute(Action): def __init__(self, args, warn=True): if isinstance(args, str): args = [args] if not (isinstance(args, list) and all(isinstance(arg), str) for arg in args): if warn: logger.warning("rule Execute argument not list of strings: %s", args) self.args = [] else: self.args = args def __str__(self): return "Execute: " + " ".join([a for a in self.args]) def evaluate(self, feature, notification: HIDPPNotification, device, last_result): if logger.isEnabledFor(logging.INFO): logger.info("Execute action: %s", self.args) subprocess.Popen(self.args) return None def data(self): return {"Execute": self.args[:]} class Later(Action): def __init__(self, args, warn=True): self.delay = 0 self.rule = Rule([]) self.components = [] if not (isinstance(args, list)): args = [args] if not (isinstance(args, list) and len(args) >= 1): if warn: logger.warning("rule Later argument not list with minimum length 1: %s", args) elif not (isinstance(args[0], (int, float))) or not 0.01 <= args[0] <= 100: if warn: logger.warning("rule Later delay not between 0.01 and 100: %s", args) else: self.delay = args[0] self.rule = Rule(args[1:], warn=warn) self.components = self.rule.components def __str__(self): return "Later: [" + str(self.delay) + ", " + ", ".join(str(c) for c in self.components) + "]" def evaluate(self, feature, notification: HIDPPNotification, device, last_result): if self.delay and self.rule: if self.delay >= 1: GLib.timeout_add_seconds(int(self.delay), Rule.once, self.rule, feature, notification, device, last_result) else: GLib.timeout_add(int(self.delay * 1000), Rule.once, self.rule, feature, notification, device, last_result) return None def data(self): data = [c.data() for c in self.components] data.insert(0, self.delay) return {"Later": data} COMPONENTS = { "Rule": Rule, "Not": Not, "Or": Or, "And": And, "Process": Process, "MouseProcess": MouseProcess, "Feature": Feature, "Report": Report, "Setting": Setting, "Modifiers": Modifiers, "Key": Key, "KeyIsDown": KeyIsDown, "Test": Test, "TestBytes": TestBytes, "MouseGesture": MouseGesture, "Active": Active, "Device": Device, "Host": Host, "KeyPress": KeyPress, "MouseScroll": MouseScroll, "MouseClick": MouseClick, "Set": Set, "Execute": Execute, "Later": Later, } built_in_rules = Rule( [ { "Rule": [ # Implement problematic keys for Craft and MX Master {"Rule": [{"Key": ["Brightness Down", "pressed"]}, {"KeyPress": "XF86_MonBrightnessDown"}]}, {"Rule": [{"Key": ["Brightness Up", "pressed"]}, {"KeyPress": "XF86_MonBrightnessUp"}]}, ] }, ] ) def key_is_down(key: NamedInt) -> bool: """Checks if given key is pressed or not.""" if key == CONTROL.MR: return mr_key_down elif CONTROL.M1 <= key <= CONTROL.M8: return bool(m_keys_down & (0x01 << (key - CONTROL.M1))) elif CONTROL.G1 <= key <= CONTROL.G32: return bool(g_keys_down & (0x01 << (key - CONTROL.G1))) return key in keys_down def evaluate_rules(feature, notification: HIDPPNotification, device): if logger.isEnabledFor(logging.DEBUG): logger.debug("evaluating rules on %s", notification) rules.evaluate(feature, notification, device, True) def process_notification(device, notification: HIDPPNotification, feature) -> None: """Processes HID++ notifications.""" global keys_down, g_keys_down, m_keys_down, mr_key_down, key_down, key_up, thumb_wheel_displacement key_down, key_up = None, None # need to keep track of keys that are down to find a new key down if notification.address == 0x00: if feature == SupportedFeature.REPROG_CONTROLS_V4: new_keys_down = struct.unpack("!4H", notification.data[:8]) for key in new_keys_down: if key and key not in keys_down: key_down = key for key in keys_down: if key and key not in new_keys_down: key_up = key keys_down = new_keys_down # and also G keys down elif feature == SupportedFeature.GKEY: new_g_keys_down = struct.unpack("<I", notification.data[:4])[0] for i in range(32): if new_g_keys_down & (0x01 << i) and not g_keys_down & (0x01 << i): key_down = CONTROL["G" + str(i + 1)] if g_keys_down & (0x01 << i) and not new_g_keys_down & (0x01 << i): key_up = CONTROL["G" + str(i + 1)] g_keys_down = new_g_keys_down # and also M keys down elif feature == SupportedFeature.MKEYS: new_m_keys_down = struct.unpack("!1B", notification.data[:1])[0] for i in range(1, 9): if new_m_keys_down & (0x01 << (i - 1)) and not m_keys_down & (0x01 << (i - 1)): key_down = CONTROL["M" + str(i)] if m_keys_down & (0x01 << (i - 1)) and not new_m_keys_down & (0x01 << (i - 1)): key_up = CONTROL["M" + str(i)] m_keys_down = new_m_keys_down # and also MR key elif feature == SupportedFeature.MR: new_mr_key_down = struct.unpack("!1B", notification.data[:1])[0] if not mr_key_down and new_mr_key_down: key_down = CONTROL["MR"] if mr_key_down and not new_mr_key_down: key_up = CONTROL["MR"] mr_key_down = new_mr_key_down # keep track of thumb wheel movement elif feature == SupportedFeature.THUMB_WHEEL: if notification.data[4] <= 0x01: # when wheel starts, zero out last movement thumb_wheel_displacement = 0 thumb_wheel_displacement += signed(notification.data[0:2]) GLib.idle_add(evaluate_rules, feature, notification, device) _XDG_CONFIG_HOME = os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser(os.path.join("~", ".config")) _file_path = os.path.join(_XDG_CONFIG_HOME, "solaar", "rules.yaml") rules = built_in_rules def _save_config_rule_file(file_name: str = _file_path): # This is a trick to show str/float/int lists in-line (inspired by https://stackoverflow.com/a/14001707) class inline_list(list): pass def blockseq_rep(dumper, data): return dumper.represent_sequence("tag:yaml.org,2002:seq", data, flow_style=True) yaml.add_representer(inline_list, blockseq_rep) def convert(elem): if isinstance(elem, list): if len(elem) == 1 and isinstance(elem[0], (int, str, float)): # All diversion classes that expect a list of scalars also support a single scalar without a list return elem[0] if all(isinstance(c, (int, str, float)) for c in elem): return inline_list([convert(c) for c in elem]) return [convert(c) for c in elem] if isinstance(elem, dict): return {k: convert(v) for k, v in elem.items()} if isinstance(elem, NamedInt): return int(elem) return elem # YAML format settings dump_settings = { "encoding": "utf-8", "explicit_start": True, "explicit_end": True, "default_flow_style": False, # 'version': (1, 3), # it would be printed for every rule } # Save only user-defined rules rules_to_save = sum((r.data()["Rule"] for r in rules.components if r.source == file_name), []) if logger.isEnabledFor(logging.INFO): logger.info("saving %d rule(s) to %s", len(rules_to_save), file_name) try: with open(file_name, "w") as f: if rules_to_save: f.write("%YAML 1.3\n") # Write version manually dump_data = [r["Rule"] for r in rules_to_save] yaml.dump_all(convert(dump_data), f, **dump_settings) except Exception as e: logger.error("failed to save to %s\n%s", file_name, e) return False return True def load_config_rule_file(): """Loads user configured rules.""" global rules if os.path.isfile(_file_path): rules = _load_rule_config(_file_path) def _load_rule_config(file_path: str) -> Rule: loaded_rules = [] try: with open(file_path) as config_file: loaded_rules = [] for loaded_rule in yaml.safe_load_all(config_file): rule = Rule(loaded_rule, source=file_path) if logger.isEnabledFor(logging.DEBUG): logger.debug("load rule: %s", rule) loaded_rules.append(rule) if logger.isEnabledFor(logging.INFO): logger.info("loaded %d rules from %s", len(loaded_rules), config_file.name) except Exception as e: logger.error("failed to load from %s\n%s", file_path, e) return Rule([Rule(loaded_rules, source=file_path), built_in_rules]) load_config_rule_file()
58,649
Python
.py
1,355
34.524723
124
0.610512
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,455
device.py
pwr-Solaar_Solaar/lib/logitech_receiver/device.py
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/ ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from __future__ import annotations import errno import logging import threading import time import typing from typing import Any from typing import Callable from typing import Optional from typing import Protocol from solaar import configuration from . import descriptors from . import exceptions from . import hidpp10 from . import hidpp10_constants from . import hidpp20 from . import settings from . import settings_templates from .common import Alert from .common import Battery from .hidpp20_constants import SupportedFeature if typing.TYPE_CHECKING: from logitech_receiver import common logger = logging.getLogger(__name__) _hidpp10 = hidpp10.Hidpp10() _hidpp20 = hidpp20.Hidpp20() class LowLevelInterface(Protocol): def open_path(self, path) -> Any: ... def find_paired_node(self, receiver_path: str, index: int, timeout: int): ... def ping(self, handle, number, long_message: bool): ... def request(self, handle, devnumber, request_id, *params, **kwargs): ... def close(self, handle, *args, **kwargs) -> bool: ... def create_device(low_level: LowLevelInterface, device_info, setting_callback=None): """Opens a Logitech Device found attached to the machine, by Linux device path. :returns: An open file handle for the found receiver, or None. """ try: handle = low_level.open_path(device_info.path) if handle: # a direct connected device might not be online (as reported by user) return Device( low_level, None, None, None, handle=handle, device_info=device_info, setting_callback=setting_callback, ) except OSError as e: logger.exception("open %s", device_info) if e.errno == errno.EACCES: raise except Exception: logger.exception("open %s", device_info) raise class Device: instances = [] read_register: Callable = hidpp10.read_register write_register: Callable = hidpp10.write_register def __init__( self, low_level: LowLevelInterface, receiver, number, online, pairing_info=None, handle=None, device_info=None, setting_callback=None, ): assert receiver or device_info if receiver: assert 0 < number <= 15 # some receivers have devices past their max # of devices self.low_level = low_level self.number = number # will be None at this point for directly connected devices self.online = online # is the device online? - gates many atempts to contact the device self.descriptor = None self.isDevice = True # some devices act as receiver so we need a property to distinguish them self.may_unpair = False self.receiver = receiver self.handle = handle self.path = device_info.path if device_info else None self.product_id = device_info.product_id if device_info else None self.hidpp_short = device_info.hidpp_short if device_info else None self.hidpp_long = device_info.hidpp_long if device_info else None self.bluetooth = device_info.bus_id == 0x0005 if device_info else False # Bluetooth needs long messages self.hid_serial = device_info.serial if device_info else None self.setting_callback = setting_callback # for changes to settings self.status_callback = None # for changes to other potentially visible aspects self.wpid = pairing_info["wpid"] if pairing_info else None # the Wireless PID is unique per device model self._kind = pairing_info["kind"] if pairing_info else None # mouse, keyboard, etc (see hidpp10.DEVICE_KIND) self._serial = pairing_info["serial"] if pairing_info else None # serial number (an 8-char hex string) self._polling_rate = pairing_info["polling"] if pairing_info else None self._power_switch = pairing_info["power_switch"] if pairing_info else None self._name = None # the full name of the model self._codename = None # Unifying peripherals report a codename. self._protocol = None # HID++ protocol version, 1.0 or 2.0 self._unitId = None # unit id (distinguishes within a model - generally the same as serial) self._modelId = None # model id (contains identifiers for the transports of the device) self._tid_map = None # map from transports to product identifiers self._persister = None # persister holds settings self._led_effects = self._firmware = self._keys = self._remap_keys = self._gestures = None self._profiles = self._backlight = self._settings = None self.registers = [] self.notification_flags = None self.battery_info = None self.link_encrypted = None self._active = None # lags self.online - is used to help determine when to setup devices self._feature_settings_checked = False self._gestures_lock = threading.Lock() self._settings_lock = threading.Lock() self._persister_lock = threading.Lock() self._notification_handlers = {} # See `add_notification_handler` self.cleanups = [] # functions to run on the device when it is closed if not self.path: self.path = self.low_level.find_paired_node(receiver.path, number, 1) if receiver else None if not self.handle: try: self.handle = self.low_level.open_path(self.path) if self.path else None except Exception: # maybe the device wasn't set up try: time.sleep(1) self.handle = self.low_level.open_path(self.path) if self.path else None except Exception: # give up self.handle = None # should this give up completely? if receiver: if not self.wpid: raise exceptions.NoSuchDevice( number=number, receiver=receiver, error="no wpid for device connected to receiver" ) self.descriptor = descriptors.get_wpid(self.wpid) if self.descriptor is None: codename = self.receiver.device_codename(self.number) # Last chance to get a descriptor, may fail if codename: self._codename = codename self.descriptor = descriptors.get_codename(self._codename) else: self.descriptor = ( descriptors.get_btid(self.product_id) if self.bluetooth else descriptors.get_usbid(self.product_id) ) if self.number is None: # for direct-connected devices get 'number' from descriptor protocol else use 0xFF if self.descriptor and self.descriptor.protocol and self.descriptor.protocol < 2.0: number = 0x00 else: number = 0xFF self.number = number self.ping() # determine whether a direct-connected device is online if self.descriptor: self._name = self.descriptor.name if self._codename is None: self._codename = self.descriptor.codename if self._kind is None: self._kind = self.descriptor.kind self._protocol = self.descriptor.protocol if self.descriptor.protocol else None self.registers = self.descriptor.registers if self.descriptor.registers else [] if self._protocol is not None: self.features = None if self._protocol < 2.0 else hidpp20.FeaturesArray(self) else: self.features = hidpp20.FeaturesArray(self) # may be a 2.0 device; if not, it will fix itself later Device.instances.append(self) def find(self, id): # find a device by serial number or unit ID assert id, "need serial number or unit ID to find a device" for device in Device.instances: if device.online and (device.unitId == id or device.serial == id): return device @property def protocol(self): if not self._protocol: self.ping() return self._protocol or 0 @property def codename(self): if not self._codename: if self.online and self.protocol >= 2.0: self._codename = _hidpp20.get_friendly_name(self) if not self._codename: self._codename = self.name.split(" ", 1)[0] if self.name else None if not self._codename and self.receiver: codename = self.receiver.device_codename(self.number) if codename: self._codename = codename elif self.protocol < 2.0: self._codename = "? (%s)" % (self.wpid or self.product_id) return self._codename or "?? (%s)" % (self.wpid or self.product_id) @property def name(self): if not self._name: if self.online and self.protocol >= 2.0: self._name = _hidpp20.get_name(self) return self._name or self._codename or "Unknown device %s" % (self.wpid or self.product_id) def get_ids(self): ids = _hidpp20.get_ids(self) if ids: self._unitId, self._modelId, self._tid_map = ids if logger.isEnabledFor(logging.INFO) and self._serial and self._serial != self._unitId: logger.info("%s: unitId %s does not match serial %s", self, self._unitId, self._serial) @property def unitId(self): if not self._unitId and self.online and self.protocol >= 2.0: self.get_ids() return self._unitId @property def modelId(self): if not self._modelId and self.online and self.protocol >= 2.0: self.get_ids() return self._modelId @property def tid_map(self): if not self._tid_map and self.online and self.protocol >= 2.0: self.get_ids() return self._tid_map @property def kind(self): if not self._kind and self.online and self.protocol >= 2.0: self._kind = _hidpp20.get_kind(self) return self._kind or "?" @property def firmware(self) -> tuple[common.FirmwareInfo]: if self._firmware is None and self.online: if self.protocol >= 2.0: self._firmware = _hidpp20.get_firmware(self) else: self._firmware = _hidpp10.get_firmware(self) return self._firmware or () @property def serial(self): return self._serial or "" @property def id(self): return self.unitId or self.serial @property def power_switch_location(self): return self._power_switch @property def polling_rate(self): if self.online and self.protocol >= 2.0: rate = _hidpp20.get_polling_rate(self) self._polling_rate = rate if rate else self._polling_rate return self._polling_rate @property def led_effects(self): if not self._led_effects and self.online and self.protocol >= 2.0: if SupportedFeature.COLOR_LED_EFFECTS in self.features: self._led_effects = hidpp20.LEDEffectsInfo(self) elif SupportedFeature.RGB_EFFECTS in self.features: self._led_effects = hidpp20.RGBEffectsInfo(self) return self._led_effects @property def keys(self): if not self._keys: if self.online and self.protocol >= 2.0: self._keys = _hidpp20.get_keys(self) or () return self._keys @property def remap_keys(self): if self._remap_keys is None: if self.online and self.protocol >= 2.0: self._remap_keys = _hidpp20.get_remap_keys(self) or () return self._remap_keys @property def gestures(self): if self._gestures is None: with self._gestures_lock: if self._gestures is None: if self.online and self.protocol >= 2.0: self._gestures = _hidpp20.get_gestures(self) or () return self._gestures @property def backlight(self): if self._backlight is None: if self.online and self.protocol >= 2.0: self._backlight = _hidpp20.get_backlight(self) return self._backlight @property def profiles(self): if self._profiles is None: if self.online and self.protocol >= 2.0: self._profiles = _hidpp20.get_profiles(self) return self._profiles def set_configuration(self, configuration_, no_reply=False): if self.online and self.protocol >= 2.0: _hidpp20.config_change(self, configuration_, no_reply=no_reply) def reset(self, no_reply=False): self.set_configuration(0, no_reply) @property def persister(self): if not self._persister: with self._persister_lock: if not self._persister: self._persister = configuration.persister(self) return self._persister @property def settings(self): if not self._settings: with self._settings_lock: if not self._settings: settings = [] if self.persister and self.descriptor and self.descriptor.settings: for sclass in self.descriptor.settings: try: setting = sclass.build(self) except Exception as e: # Do nothing if the device is offline setting = None if self.online: raise e if setting is not None: settings.append(setting) self._settings = settings if not self._feature_settings_checked: with self._settings_lock: if not self._feature_settings_checked: self._feature_settings_checked = settings_templates.check_feature_settings(self, self._settings) return self._settings def battery(self): # None or level, next, status, voltage if self.protocol < 2.0: return _hidpp10.get_battery(self) else: battery_feature = self.persister.get("_battery", None) if self.persister else None if battery_feature != 0: result = _hidpp20.get_battery(self, battery_feature) try: feature, battery = result if self.persister and battery_feature is None: self.persister["_battery"] = feature return battery except Exception: if self.persister and battery_feature is None: self.persister["_battery"] = result def set_battery_info(self, info): """Update battery information for device, calling changed callback if necessary""" if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: battery %s, %s", self, info.level, info.status) if info.level is None and self.battery_info: # use previous level if missing from new information info.level = self.battery_info.level changed = self.battery_info != info self.battery_info, old_info = info, self.battery_info if old_info is None: old_info = Battery(None, None, None, None) alert, reason = Alert.NONE, None if not info.ok(): logger.warning("%s: battery %d%%, ALERT %s", self, info.level, info.status) if old_info.status != info.status: alert = Alert.NOTIFICATION | Alert.ATTENTION reason = info.to_str() if changed or reason: # update the leds on the device, if any _hidpp10.set_3leds(self, info.level, charging=info.charging(), warning=bool(alert)) self.changed(active=True, alert=alert, reason=reason) # Retrieve and regularize battery status def read_battery(self): if self.online: battery = self.battery() self.set_battery_info(battery if battery is not None else Battery(None, None, None, None)) def changed(self, active=None, alert=Alert.NONE, reason=None, push=False): """The status of the device had changed, so invoke the status callback. Also push notifications and settings to the device when necessary.""" if active is not None: self.online = active was_active, self._active = self._active, active if active: # Push settings for new devices when devices request software reconfiguration # and when devices become active if they don't have wireless device status feature, if ( was_active is None or not was_active or push and (not self.features or SupportedFeature.WIRELESS_DEVICE_STATUS not in self.features) ): if logger.isEnabledFor(logging.INFO): logger.info("%s pushing device settings %s", self, self.settings) settings.apply_all_settings(self) if not was_active: if self.protocol < 2.0: # Make sure to set notification flags on the device self.notification_flags = self.enable_connection_notifications() else: self.set_configuration(0x11) # signal end of configuration self.read_battery() # battery information may have changed so try to read it now elif was_active and self.receiver: # need to set configuration pending flag in receiver hidpp10.set_configuration_pending_flags(self.receiver, 0xFF) if logger.isEnabledFor(logging.DEBUG): logger.debug("device %d changed: active=%s %s", self.number, self._active, self.battery_info) if self.status_callback is not None: self.status_callback(self, alert, reason) def enable_connection_notifications(self, enable=True): """Enable or disable device (dis)connection notifications on this receiver.""" if not bool(self.receiver) or self.protocol >= 2.0: return False if enable: set_flag_bits = ( hidpp10_constants.NOTIFICATION_FLAG.battery_status | hidpp10_constants.NOTIFICATION_FLAG.ui | hidpp10_constants.NOTIFICATION_FLAG.configuration_complete ) else: set_flag_bits = 0 ok = _hidpp10.set_notification_flags(self, set_flag_bits) if not ok: logger.warning("%s: failed to %s device notifications", self, "enable" if enable else "disable") flag_bits = _hidpp10.get_notification_flags(self) if logger.isEnabledFor(logging.INFO): flag_names = None if flag_bits is None else tuple(hidpp10_constants.NOTIFICATION_FLAG.flag_names(flag_bits)) logger.info("%s: device notifications %s %s", self, "enabled" if enable else "disabled", flag_names) return flag_bits if ok else None def add_notification_handler(self, id: str, fn): """Adds the notification handling callback `fn` to this device under name `id`. If a callback has already been registered under this name, it's replaced with the argument. The callback will be invoked whenever the device emits an event message, and the resulting notification hasn't been handled by another handler on this device (order is not guaranteed, so handlers should not overlap in functionality). The callback should have type `(PairedDevice, Notification) -> Optional[bool]`. It should return `None` if it hasn't handled the notification, return `True` if it did so successfully and return `False` if an error should be reported (malformed notification, etc). """ self._notification_handlers[id] = fn def remove_notification_handler(self, id: str): """Unregisters the notification handler under name `id`.""" if id not in self._notification_handlers and logger.isEnabledFor(logging.INFO): logger.info(f"Tried to remove nonexistent notification handler {id} from device {self}.") else: del self._notification_handlers[id] def handle_notification(self, n) -> Optional[bool]: for h in self._notification_handlers.values(): ret = h(self, n) if ret is not None: return ret return None def request(self, request_id, *params, no_reply=False): if self: long = self.hidpp_long is True or ( self.hidpp_long is None and (self.bluetooth or self._protocol is not None and self._protocol >= 2.0) ) return self.low_level.request( self.handle or self.receiver.handle, self.number, request_id, *params, no_reply=no_reply, long_message=long, protocol=self.protocol, ) def feature_request(self, feature, function=0x00, *params, no_reply=False): if self.protocol >= 2.0: return hidpp20.feature_request(self, feature, function, *params, no_reply=no_reply) def ping(self): """Checks if the device is online, returns True of False""" long = self.hidpp_long is True or ( self.hidpp_long is None and (self.bluetooth or self._protocol is not None and self._protocol >= 2.0) ) handle = self.handle or self.receiver.handle protocol = self.low_level.ping(handle, self.number, long_message=long) self.online = protocol is not None if protocol: self._protocol = protocol return self.online def notify_devices(self): # no need to notify, as there are none pass def close(self): handle, self.handle = self.handle, None if self in Device.instances: Device.instances.remove(self) if hasattr(self, "cleanups"): for cleanup in self.cleanups: cleanup(self) return handle and self.low_level.close(handle) def __index__(self): return self.number __int__ = __index__ def __eq__(self, other): return other is not None and self._kind == other._kind and self.wpid == other.wpid def __ne__(self, other): return other is None or self.kind != other.kind or self.wpid != other.wpid def __hash__(self): return self.wpid.__hash__() def __bool__(self): return self.wpid is not None and self.number in self.receiver if self.receiver else self.handle is not None __nonzero__ = __bool__ def status_string(self): return self.battery_info.to_str() if self.battery_info is not None else "" def __str__(self): try: name = self._name or self._codename or "?" except exceptions.NoSuchDevice: name = "name not available" return f"<Device({int(self.number)},{self.wpid or self.product_id},{name},{self.serial})>" __repr__ = __str__ def __del__(self): self.close()
24,487
Python
.py
512
37.0625
120
0.61684
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,456
hidpp20.py
pwr-Solaar_Solaar/lib/logitech_receiver/hidpp20.py
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/ ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from __future__ import annotations import logging import socket import struct import threading from typing import Any from typing import Dict from typing import Generator from typing import List from typing import Optional from typing import Tuple import yaml from solaar.i18n import _ from typing_extensions import Protocol from . import common from . import exceptions from . import hidpp10_constants from . import special_keys from .common import Battery from .common import BatteryLevelApproximation from .common import BatteryStatus from .common import FirmwareKind from .common import NamedInt from .hidpp20_constants import CHARGE_LEVEL from .hidpp20_constants import CHARGE_STATUS from .hidpp20_constants import CHARGE_TYPE from .hidpp20_constants import DEVICE_KIND from .hidpp20_constants import ERROR from .hidpp20_constants import GESTURE from .hidpp20_constants import SupportedFeature logger = logging.getLogger(__name__) FixedBytes5 = bytes KIND_MAP = {kind: hidpp10_constants.DEVICE_KIND[str(kind)] for kind in DEVICE_KIND} class Device(Protocol): def feature_request(self, feature, function=0x00, *params, no_reply=False) -> Any: ... @property def features(self) -> Any: ... @property def _gestures(self) -> Any: ... @property def _backlight(self) -> Any: ... @property def _profiles(self) -> Any: ... class FeaturesArray(dict): def __init__(self, device): assert device is not None self.supported = True # Actually don't know whether it is supported yet self.device = device self.inverse = {} self.version = {} self.count = 0 def _check(self) -> bool: if not self.device.online: return False if self.supported is False: return False if self.device.protocol and self.device.protocol < 2.0: self.supported = False return False if self.count > 0: return True reply = self.device.request(0x0000, struct.pack("!H", SupportedFeature.FEATURE_SET)) if reply is not None: fs_index = reply[0] if fs_index: count = self.device.request(fs_index << 8) if count is None: logger.warning("FEATURE_SET found, but failed to read features count") return False else: self.count = count[0] + 1 # ROOT feature not included in count self[SupportedFeature.ROOT] = 0 self[SupportedFeature.FEATURE_SET] = fs_index return True else: self.supported = False return False def get_feature(self, index: int) -> SupportedFeature | None: feature = self.inverse.get(index) if feature is not None: return feature elif self._check(): feature = self.inverse.get(index) if feature is not None: return feature response = self.device.feature_request(SupportedFeature.FEATURE_SET, 0x10, index) if response: data = struct.unpack("!H", response[:2])[0] try: feature = SupportedFeature(data) except ValueError: feature = f"unknown:{data:04X}" self[feature] = index self.version[feature] = response[3] return feature def enumerate(self): # return all features and their index, ordered by index if self._check(): for index in range(self.count): feature = self.get_feature(index) yield feature, index def get_feature_version(self, feature: NamedInt) -> Optional[int]: if self[feature]: return self.version.get(feature, 0) def __contains__(self, feature: NamedInt) -> bool: try: index = self.__getitem__(feature) return index is not None and index is not False except exceptions.FeatureCallError: return False def __getitem__(self, feature: NamedInt) -> Optional[int]: index = super().get(feature) if index is not None: return index elif self._check(): index = super().get(feature) if index is not None: return index response = self.device.request(0x0000, struct.pack("!H", feature)) if response: index = response[0] self[feature] = index if index else False self.version[feature] = response[2] return index if index else False def __setitem__(self, feature, index): if isinstance(super().get(feature), int): self.inverse.pop(super().get(feature)) super().__setitem__(feature, index) if index is not False: self.inverse[index] = feature def __delitem__(self, feature): raise ValueError("Don't delete features from FeatureArray") def __len__(self) -> int: return self.count __bool__ = __nonzero__ = _check class ReprogrammableKey: """Information about a control present on a device with the `REPROG_CONTROLS` feature. Ref: https://drive.google.com/file/d/0BxbRzx7vEV7eU3VfMnRuRXktZ3M/view Read-only properties: - index {int} -- index in the control ID table - key {NamedInt} -- the name of this control - default_task {NamedInt} -- the native function of this control - flags {List[str]} -- capabilities and desired software handling of the control """ def __init__(self, device: Device, index, cid, tid, flags): self._device = device self.index = index self._cid = cid self._tid = tid self._flags = flags @property def key(self) -> NamedInt: return special_keys.CONTROL[self._cid] @property def default_task(self) -> NamedInt: """NOTE: This NamedInt is a bit mixed up, because its value is the Control ID while the name is the Control ID's native task. But this makes more sense than presenting details of controls vs tasks in the interface. The same convention applies to `mapped_to`, `remappable_to`, `remap` in `ReprogrammableKeyV4`.""" task = str(special_keys.TASK[self._tid]) return NamedInt(self._cid, task) @property def flags(self) -> List[str]: return special_keys.KEY_FLAG.flag_names(self._flags) class ReprogrammableKeyV4(ReprogrammableKey): """Information about a control present on a device with the `REPROG_CONTROLS_V4` feature. Ref (v2): https://lekensteyn.nl/files/logitech/x1b04_specialkeysmsebuttons.html Ref (v4): https://drive.google.com/file/d/10imcbmoxTJ1N510poGdsviEhoFfB_Ua4/view Contains all the functionality of `ReprogrammableKey` plus remapping keys and /diverting/ them in order to handle keypresses in a custom way. Additional read-only properties: - pos {int} -- position of this control on the device; 1-16 for FN-keys, otherwise 0 - group {int} -- the group this control belongs to; other controls with this group in their `group_mask` can be remapped to this control - group_mask {List[str]} -- this control can be remapped to any control ID in these groups - mapped_to {NamedInt} -- which action this control is mapped to; usually itself - remappable_to {List[NamedInt]} -- list of actions which this control can be remapped to - mapping_flags {List[str]} -- mapping flags set on the control """ def __init__(self, device: Device, index, cid, tid, flags, pos, group, gmask): ReprogrammableKey.__init__(self, device, index, cid, tid, flags) self.pos = pos self.group = group self._gmask = gmask self._mapping_flags = None self._mapped_to = None @property def group_mask(self) -> Generator[str]: return common.flag_names(special_keys.CIDGroupBit, self._gmask) @property def mapped_to(self) -> NamedInt: if self._mapped_to is None: self._getCidReporting() self._device.keys._ensure_all_keys_queried() task = str(special_keys.TASK[self._device.keys.cid_to_tid[self._mapped_to]]) return NamedInt(self._mapped_to, task) @property def remappable_to(self) -> common.NamedInts: self._device.keys._ensure_all_keys_queried() ret = common.UnsortedNamedInts() if self.group_mask: # only keys with a non-zero gmask are remappable ret[self.default_task] = self.default_task # it should always be possible to map the key to itself for g in self.group_mask: g = special_keys.CidGroup[str(g)] for tgt_cid in self._device.keys.group_cids[g]: tgt_task = str(special_keys.TASK[self._device.keys.cid_to_tid[tgt_cid]]) tgt_task = NamedInt(tgt_cid, tgt_task) if tgt_task != self.default_task: # don't put itself in twice ret[tgt_task] = tgt_task return ret @property def mapping_flags(self) -> List[str]: if self._mapping_flags is None: self._getCidReporting() return special_keys.MAPPING_FLAG.flag_names(self._mapping_flags) def set_diverted(self, value: bool): """If set, the control is diverted temporarily and reports presses as HID++ events.""" flags = {special_keys.MAPPING_FLAG.diverted: value} self._setCidReporting(flags=flags) def set_persistently_diverted(self, value: bool): """If set, the control is diverted permanently and reports presses as HID++ events.""" flags = {special_keys.MAPPING_FLAG.persistently_diverted: value} self._setCidReporting(flags=flags) def set_rawXY_reporting(self, value: bool): """If set, the mouse temporarily reports all its raw XY events while this control is pressed as HID++ events.""" flags = {special_keys.MAPPING_FLAG.raw_XY_diverted: value} self._setCidReporting(flags=flags) def remap(self, to: NamedInt): """Temporarily remaps this control to another action.""" self._setCidReporting(remap=int(to)) def _getCidReporting(self): try: mapped_data = self._device.feature_request( SupportedFeature.REPROG_CONTROLS_V4, 0x20, *tuple(struct.pack("!H", self._cid)), ) if mapped_data: cid, mapping_flags_1, mapped_to = struct.unpack("!HBH", mapped_data[:5]) if cid != self._cid and logger.isEnabledFor(logging.WARNING): logger.warning( f"REPROG_CONTROLS_V4 endpoint getCidReporting on device {self._device} replied " + f"with a different control ID ({cid}) than requested ({self._cid})." ) self._mapped_to = mapped_to if mapped_to != 0 else self._cid if len(mapped_data) > 5: (mapping_flags_2,) = struct.unpack("!B", mapped_data[5:6]) else: mapping_flags_2 = 0 self._mapping_flags = mapping_flags_1 | (mapping_flags_2 << 8) else: raise exceptions.FeatureCallError(msg="No reply from device.") except exceptions.FeatureCallError: # if the key hasn't ever been configured only produce a warning if logger.isEnabledFor(logging.WARNING): logger.warning( f"Feature Call Error in _getCidReporting on device {self._device} for cid {self._cid} - use defaults" ) # Clear flags and set mapping target to self self._mapping_flags = 0 self._mapped_to = self._cid def _setCidReporting(self, flags: Dict[NamedInt, bool] = None, remap: int = 0): """Sends a `setCidReporting` request with the given parameters. Raises an exception if the parameters are invalid. Parameters ---------- flags A dictionary of which mapping flags to set/unset. remap Which control ID to remap to; or 0 to keep current mapping. """ flags = flags if flags else {} # See flake8 B006 # if special_keys.MAPPING_FLAG.raw_XY_diverted in flags and flags[special_keys.MAPPING_FLAG.raw_XY_diverted]: # We need diversion to report raw XY, so divert temporarily (since XY reporting is also temporary) # flags[special_keys.MAPPING_FLAG.diverted] = True # if special_keys.MAPPING_FLAG.diverted in flags and not flags[special_keys.MAPPING_FLAG.diverted]: # flags[special_keys.MAPPING_FLAG.raw_XY_diverted] = False # The capability required to set a given reporting flag. FLAG_TO_CAPABILITY = { special_keys.MAPPING_FLAG.diverted: special_keys.KEY_FLAG.divertable, special_keys.MAPPING_FLAG.persistently_diverted: special_keys.KEY_FLAG.persistently_divertable, special_keys.MAPPING_FLAG.analytics_key_events_reporting: special_keys.KEY_FLAG.analytics_key_events, special_keys.MAPPING_FLAG.force_raw_XY_diverted: special_keys.KEY_FLAG.force_raw_XY, special_keys.MAPPING_FLAG.raw_XY_diverted: special_keys.KEY_FLAG.raw_XY, } bfield = 0 for f, v in flags.items(): if v and FLAG_TO_CAPABILITY[f] not in self.flags: raise exceptions.FeatureNotSupported( msg=f'Tried to set mapping flag "{f}" on control "{self.key}" ' + f'which does not support "{FLAG_TO_CAPABILITY[f]}" on device {self._device}.' ) bfield |= int(f) if v else 0 bfield |= int(f) << 1 # The 'Xvalid' bit if self._mapping_flags: # update flags if already read if v: self._mapping_flags |= int(f) else: self._mapping_flags &= ~int(f) if remap != 0 and remap not in self.remappable_to: raise exceptions.FeatureNotSupported( msg=f'Tried to remap control "{self.key}" to a control ID {remap} which it is not remappable to ' + f"on device {self._device}." ) if remap != 0: # update mapping if changing (even if not already read) self._mapped_to = remap pkt = tuple(struct.pack("!HBH", self._cid, bfield & 0xFF, remap)) # TODO: to fully support version 4 of REPROG_CONTROLS_V4, append `(bfield >> 8) & 0xff` here. # But older devices might behave oddly given that byte, so we don't send it. ret = self._device.feature_request(SupportedFeature.REPROG_CONTROLS_V4, 0x30, *pkt) if ret is None or struct.unpack("!BBBBB", ret[:5]) != pkt and logger.isEnabledFor(logging.DEBUG): logger.debug(f"REPROG_CONTROLS_v4 setCidReporting on device {self._device} didn't echo request packet.") class PersistentRemappableAction: def __init__(self, device, index, cid, actionId, remapped, modifierMask, cidStatus): self._device = device self.index = index self._cid = cid self.actionId = actionId self.remapped = remapped self._modifierMask = modifierMask self.cidStatus = cidStatus @property def key(self) -> NamedInt: return special_keys.CONTROL[self._cid] @property def actionType(self) -> NamedInt: return special_keys.ACTIONID[self.actionId] @property def action(self): if self.actionId == special_keys.ACTIONID.Empty: return None elif self.actionId == special_keys.ACTIONID.Key: return "Key: " + str(self.modifiers) + str(self.remapped) elif self.actionId == special_keys.ACTIONID.Mouse: return "Mouse Button: " + str(self.remapped) elif self.actionId == special_keys.ACTIONID.Xdisp: return "X Displacement " + str(self.remapped) elif self.actionId == special_keys.ACTIONID.Ydisp: return "Y Displacement " + str(self.remapped) elif self.actionId == special_keys.ACTIONID.Vscroll: return "Vertical Scroll " + str(self.remapped) elif self.actionId == special_keys.ACTIONID.Hscroll: return "Horizontal Scroll: " + str(self.remapped) elif self.actionId == special_keys.ACTIONID.Consumer: return "Consumer: " + str(self.remapped) elif self.actionId == special_keys.ACTIONID.Internal: return "Internal Action " + str(self.remapped) elif self.actionId == special_keys.ACTIONID.Internal: return "Power " + str(self.remapped) else: return "Unknown" @property def modifiers(self): return special_keys.modifiers[self._modifierMask] @property def data_bytes(self): return ( common.int2bytes(self.actionId, 1) + common.int2bytes(self.remapped, 2) + common.int2bytes(self._modifierMask, 1) ) def remap(self, data_bytes): cid = common.int2bytes(self._cid, 2) if common.bytes2int(data_bytes) == special_keys.KEYS_Default: # map back to default self._device.feature_request(SupportedFeature.PERSISTENT_REMAPPABLE_ACTION, 0x50, cid, 0xFF) self._device.remap_keys._query_key(self.index) return self._device.remap_keys.keys[self.index].data_bytes else: self.actionId, self.remapped, self._modifierMask = struct.unpack("!BHB", data_bytes) self.cidStatus = 0x01 self._device.feature_request(SupportedFeature.PERSISTENT_REMAPPABLE_ACTION, 0x40, cid, 0xFF, data_bytes) return True class KeysArray: """A sequence of key mappings supported by a HID++ 2.0 device.""" def __init__(self, device, count, version): assert device is not None self.device = device self.lock = threading.Lock() if SupportedFeature.REPROG_CONTROLS_V4 in self.device.features: self.keyversion = SupportedFeature.REPROG_CONTROLS_V4 elif SupportedFeature.REPROG_CONTROLS_V2 in self.device.features: self.keyversion = SupportedFeature.REPROG_CONTROLS_V2 else: if logger.isEnabledFor(logging.ERROR): logger.error(f"Trying to read keys on device {device} which has no REPROG_CONTROLS(_VX) support.") self.keyversion = None self.keys = [None] * count def _ensure_all_keys_queried(self): """The retrieval of key information is lazy, but for certain functionality we need to know all keys. This function makes sure that's the case.""" with self.lock: # don't want two threads doing this for i, k in enumerate(self.keys): if k is None: self._query_key(i) def __getitem__(self, index): if isinstance(index, int): if index < 0 or index >= len(self.keys): raise IndexError(index) if self.keys[index] is None: self._query_key(index) return self.keys[index] elif isinstance(index, slice): indices = index.indices(len(self.keys)) return [self.__getitem__(i) for i in range(*indices)] def index(self, value): self._ensure_all_keys_queried() for index, k in enumerate(self.keys): if k is not None and int(value) == int(k.key): return index def __iter__(self): for k in range(0, len(self.keys)): yield self.__getitem__(k) def __len__(self): return len(self.keys) class KeysArrayV2(KeysArray): def __init__(self, device: Device, count, version=1): super().__init__(device, count, version) """The mapping from Control IDs to their native Task IDs. For example, Control "Left Button" is mapped to Task "Left Click". When remapping controls, we point the control we want to remap at a target Control ID rather than a target Task ID. This has the effect of performing the native task of the target control, even if the target itself is also remapped. So remapping is not recursive.""" self.cid_to_tid = {} """The mapping from Control ID groups to Controls IDs that belong to it. A key k can only be remapped to targets in groups within k.group_mask.""" self.group_cids = {g: [] for g in special_keys.CidGroup} def _query_key(self, index: int): if index < 0 or index >= len(self.keys): raise IndexError(index) keydata = self.device.feature_request(SupportedFeature.REPROG_CONTROLS, 0x10, index) if keydata: cid, tid, flags = struct.unpack("!HHB", keydata[:5]) self.keys[index] = ReprogrammableKey(self.device, index, cid, tid, flags) self.cid_to_tid[cid] = tid elif logger.isEnabledFor(logging.WARNING): logger.warning(f"Key with index {index} was expected to exist but device doesn't report it.") class KeysArrayV4(KeysArrayV2): def __init__(self, device, count): super().__init__(device, count, 4) def _query_key(self, index: int): if index < 0 or index >= len(self.keys): raise IndexError(index) keydata = self.device.feature_request(SupportedFeature.REPROG_CONTROLS_V4, 0x10, index) if keydata: cid, tid, flags1, pos, group, gmask, flags2 = struct.unpack("!HHBBBBB", keydata[:9]) flags = flags1 | (flags2 << 8) self.keys[index] = ReprogrammableKeyV4(self.device, index, cid, tid, flags, pos, group, gmask) self.cid_to_tid[cid] = tid if group != 0: # 0 = does not belong to a group self.group_cids[special_keys.CidGroup(group)].append(cid) elif logger.isEnabledFor(logging.WARNING): logger.warning(f"Key with index {index} was expected to exist but device doesn't report it.") # we are only interested in the current host, so use 0xFF for the host throughout class KeysArrayPersistent(KeysArray): def __init__(self, device, count): super().__init__(device, count, 5) self._capabilities = None @property def capabilities(self): if self._capabilities is None and self.device.online: capabilities = self.device.feature_request(SupportedFeature.PERSISTENT_REMAPPABLE_ACTION, 0x00) assert capabilities, "Oops, persistent remappable key capabilities cannot be retrieved!" self._capabilities = struct.unpack("!H", capabilities[:2])[0] # flags saying what the mappings are possible return self._capabilities def _query_key(self, index: int): if index < 0 or index >= len(self.keys): raise IndexError(index) keydata = self.device.feature_request(SupportedFeature.PERSISTENT_REMAPPABLE_ACTION, 0x20, index, 0xFF) if keydata: key = struct.unpack("!H", keydata[:2])[0] mapped_data = self.device.feature_request( SupportedFeature.PERSISTENT_REMAPPABLE_ACTION, 0x30, key >> 8, key & 0xFF, 0xFF, ) if mapped_data: _ignore, _ignore, actionId, remapped, modifiers, status = struct.unpack("!HBBHBB", mapped_data[:8]) else: actionId = remapped = modifiers = status = 0 actionId = special_keys.ACTIONID[actionId] if actionId == special_keys.ACTIONID.Key: remapped = special_keys.USB_HID_KEYCODES[remapped] elif actionId == special_keys.ACTIONID.Mouse: remapped = special_keys.MOUSE_BUTTONS[remapped] elif actionId == special_keys.ACTIONID.Hscroll: remapped = special_keys.HORIZONTAL_SCROLL[remapped] elif actionId == special_keys.ACTIONID.Consumer: remapped = special_keys.HID_CONSUMERCODES[remapped] elif actionId == special_keys.ACTIONID.Empty: # purge data from empty value remapped = modifiers = 0 self.keys[index] = PersistentRemappableAction( self.device, index, key, actionId, remapped, modifiers, status, ) elif logger.isEnabledFor(logging.WARNING): logger.warning(f"Key with index {index} was expected to exist but device doesn't report it.") # Param Ids for feature GESTURE_2 PARAM = common.NamedInts( ExtraCapabilities=1, # not suitable for use PixelZone=2, # 4 2-byte integers, left, bottom, width, height; pixels RatioZone=3, # 4 bytes, left, bottom, width, height; unit 1/240 pad size ScaleFactor=4, # 2-byte integer, with 256 as normal scale ) PARAM._fallback = lambda x: f"unknown:{x:04X}" class SubParam: __slots__ = ("id", "length", "minimum", "maximum", "widget") def __init__(self, id, length, minimum=None, maximum=None, widget=None): self.id = id self.length = length self.minimum = minimum if minimum is not None else 0 self.maximum = maximum if maximum is not None else ((1 << 8 * length) - 1) self.widget = widget if widget is not None else "Scale" def __str__(self): return self.id def __repr__(self): return self.id SUB_PARAM = { # (byte count, minimum, maximum) PARAM["ExtraCapabilities"]: None, # ignore PARAM["PixelZone"]: ( # TODO: replace min and max with the correct values SubParam("left", 2, 0x0000, 0xFFFF, "SpinButton"), SubParam("bottom", 2, 0x0000, 0xFFFF, "SpinButton"), SubParam("width", 2, 0x0000, 0xFFFF, "SpinButton"), SubParam("height", 2, 0x0000, 0xFFFF, "SpinButton"), ), PARAM["RatioZone"]: ( # TODO: replace min and max with the correct values SubParam("left", 1, 0x00, 0xFF, "SpinButton"), SubParam("bottom", 1, 0x00, 0xFF, "SpinButton"), SubParam("width", 1, 0x00, 0xFF, "SpinButton"), SubParam("height", 1, 0x00, 0xFF, "SpinButton"), ), PARAM["ScaleFactor"]: (SubParam("scale", 2, 0x002E, 0x01FF, "Scale"),), } # Spec Ids for feature GESTURE_2 SPEC = common.NamedInts( DVI_field_width=1, field_widths=2, period_unit=3, resolution=4, multiplier=5, sensor_size=6, finger_width_and_height=7, finger_major_minor_axis=8, finger_force=9, zone=10, ) SPEC._fallback = lambda x: f"unknown:{x:04X}" # Action Ids for feature GESTURE_2 ACTION_ID = common.NamedInts( MovePointer=1, ScrollHorizontal=2, WheelScrolling=3, ScrollVertial=4, ScrollOrPageXY=5, ScrollOrPageHorizontal=6, PageScreen=7, Drag=8, SecondaryDrag=9, Zoom=10, ScrollHorizontalOnly=11, ScrollVerticalOnly=12, ) ACTION_ID._fallback = lambda x: f"unknown:{x:04X}" class Gesture: def __init__(self, device, low, high, next_index, next_diversion_index): self._device = device self.id = low self.gesture = GESTURE[low] self.can_be_enabled = high & 0x01 self.can_be_diverted = high & 0x02 self.show_in_ui = high & 0x04 self.desired_software_default = high & 0x08 self.persistent = high & 0x10 self.default_enabled = high & 0x20 self.index = next_index if self.can_be_enabled or self.default_enabled else None self.diversion_index = next_diversion_index if self.can_be_diverted else None self._enabled = None self._diverted = None def _offset_mask(self, index): # offset and mask if index is not None: offset = index >> 3 # 8 gestures per byte mask = 0x1 << (index % 8) return offset, mask else: return None, None def enable_offset_mask(self): return self._offset_mask(self.index) def diversion_offset_mask(self): return self._offset_mask(self.diversion_index) def enabled(self): # is the gesture enabled? if self._enabled is None and self.index is not None: offset, mask = self.enable_offset_mask() result = self._device.feature_request(SupportedFeature.GESTURE_2, 0x10, offset, 0x01, mask) self._enabled = bool(result[0] & mask) if result else None return self._enabled def set(self, enable): # enable or disable the gesture if not self.can_be_enabled: return None if self.index is not None: offset, mask = self.enable_offset_mask() reply = self._device.feature_request( SupportedFeature.GESTURE_2, 0x20, offset, 0x01, mask, mask if enable else 0x00 ) return reply def diverted(self): # is the gesture diverted? if self._diverted is None and self.diversion_index is not None: offset, mask = self.diversion_offset_mask() result = self._device.feature_request(SupportedFeature.GESTURE_2, 0x30, offset, 0x01, mask) self._diverted = bool(result[0] & mask) if result else None return self._diverted def divert(self, diverted): # divert or undivert the gesture if not self.can_be_diverted: return None if self.diversion_index is not None: offset, mask = self.diversion_offset_mask() reply = self._device.feature_request( SupportedFeature.GESTURE_2, 0x40, offset, 0x01, mask, mask if diverted else 0x00, ) return reply def as_int(self): return self.gesture def __int__(self): return self.id def __repr__(self): return f"<Gesture {self.gesture} index={self.index} diversion_index={self.diversion_index}>" # allow a gesture to be used as a settings reader/writer to enable and disable the gesture read = enabled write = set class Param: def __init__(self, device, low, high, next_param_index): self._device = device self.id = low self.param = PARAM[low] self.size = high & 0x0F self.show_in_ui = bool(high & 0x1F) self._value = None self._default_value = None self.index = next_param_index @property def sub_params(self): return SUB_PARAM.get(self.id, None) @property def value(self): return self._value if self._value is not None else self.read() def read(self): # returns the bytes for the parameter result = self._device.feature_request(SupportedFeature.GESTURE_2, 0x70, self.index, 0xFF) if result: self._value = common.bytes2int(result[: self.size]) return self._value @property def default_value(self): if self._default_value is None: self._default_value = self._read_default() return self._default_value def _read_default(self): result = self._device.feature_request(SupportedFeature.GESTURE_2, 0x60, self.index, 0xFF) if result: self._default_value = common.bytes2int(result[: self.size]) return self._default_value def write(self, bytes): self._value = bytes return self._device.feature_request(SupportedFeature.GESTURE_2, 0x80, self.index, bytes, 0xFF) def __str__(self): return str(self.param) def __int__(self): return self.id class Spec: def __init__(self, device, low, high): self._device = device self.id = low self.spec = SPEC[low] self.byte_count = high & 0x0F self._value = None @property def value(self): if self._value is None: self._value = self.read() return self._value def read(self): try: value = self._device.feature_request(SupportedFeature.GESTURE_2, 0x50, self.id, 0xFF) except exceptions.FeatureCallError: # some calls produce an error (notably spec 5 multiplier on K400Plus) if logger.isEnabledFor(logging.WARNING): logger.warning( f"Feature Call Error reading Gesture Spec on device {self._device} for spec {self.id} - use None" ) return None return common.bytes2int(value[: self.byte_count]) def __repr__(self): return f"[{self.spec}={self.value}]" class Gestures: """Information about the gestures that a device supports. Right now only some information fields are supported. WARNING: Assumes that parameters are always global, which is not the case. """ def __init__(self, device): self.device = device self.gestures = {} self.params = {} self.specs = {} index = 0 next_gesture_index = next_divsn_index = next_param_index = 0 field_high = 0x00 while field_high != 0x01: # end of fields # retrieve the next eight fields fields = device.feature_request(SupportedFeature.GESTURE_2, 0x00, index >> 8, index & 0xFF) if not fields: break for offset in range(8): field_high = fields[offset * 2] field_low = fields[offset * 2 + 1] if field_high == 0x1: # end of fields break elif field_high & 0x80: gesture = Gesture(device, field_low, field_high, next_gesture_index, next_divsn_index) next_gesture_index = next_gesture_index if gesture.index is None else next_gesture_index + 1 next_divsn_index = next_divsn_index if gesture.diversion_index is None else next_divsn_index + 1 self.gestures[gesture.gesture] = gesture elif field_high & 0xF0 == 0x30 or field_high & 0xF0 == 0x20: param = Param(device, field_low, field_high, next_param_index) next_param_index = next_param_index + 1 self.params[param.param] = param elif field_high == 0x04: if field_low != 0x00: logger.error(f"Unimplemented GESTURE_2 grouping {field_low} {field_high} found.") elif field_high & 0xF0 == 0x40: spec = Spec(device, field_low, field_high) self.specs[spec.spec] = spec else: logger.warning(f"Unimplemented GESTURE_2 field {field_low} {field_high} found.") index += 1 def gesture(self, gesture): return self.gestures.get(gesture, None) def gesture_enabled(self, gesture): # is the gesture enabled? g = self.gestures.get(gesture, None) return g.enabled() if g else None def enable_gesture(self, gesture): g = self.gestures.get(gesture, None) return g.set(True) if g else None def disable_gesture(self, gesture): g = self.gestures.get(gesture, None) return g.set(False) if g else None def param(self, param): return self.params.get(param, None) def get_param(self, param): g = self.params.get(param, None) return g.read() if g else None def set_param(self, param, value): g = self.params.get(param, None) return g.write(value) if g else None class Backlight: """Information about the current settings of x1982 Backlight2 v3, but also works for previous versions""" def __init__(self, device): response = device.feature_request(SupportedFeature.BACKLIGHT2, 0x00) if not response: raise exceptions.FeatureCallError(msg="No reply from device.") self.device = device self.enabled, self.options, supported, effects, self.level, self.dho, self.dhi, self.dpow = struct.unpack( "<BBBHBHHH", response[:12] ) self.auto_supported = supported & 0x08 self.temp_supported = supported & 0x10 self.perm_supported = supported & 0x20 self.mode = (self.options >> 3) & 0x03 def write(self): self.options = (self.options & 0x07) | (self.mode << 3) level = self.level if self.mode == 0x3 else 0 data_bytes = struct.pack("<BBBBHHH", self.enabled, self.options, 0xFF, level, self.dho, self.dhi, self.dpow) return self.device.feature_request(SupportedFeature.BACKLIGHT2, 0x10, data_bytes) class LEDParam: color = "color" speed = "speed" period = "period" intensity = "intensity" ramp = "ramp" form = "form" saturation = "saturation" LEDRampChoices = common.NamedInts(default=0, yes=1, no=2) LEDFormChoices = common.NamedInts(default=0, sine=1, square=2, triangle=3, sawtooth=4, sharkfin=5, exponential=6) LEDParamSize = { LEDParam.color: 3, LEDParam.speed: 1, LEDParam.period: 2, LEDParam.intensity: 1, LEDParam.ramp: 1, LEDParam.form: 1, LEDParam.saturation: 1, } # not implemented from x8070 Wave=4, Stars=5, Press=6, Audio=7 # not implemented from x8071 Custom=12, Kitt=13, HSVPulsing=20, # WaveC=22, RippleC=23, SignatureActive=24, SignaturePassive=25 LEDEffects = { 0x00: [NamedInt(0x00, _("Disabled")), {}], 0x01: [NamedInt(0x01, _("Static")), {LEDParam.color: 0, LEDParam.ramp: 3}], 0x02: [NamedInt(0x02, _("Pulse")), {LEDParam.color: 0, LEDParam.speed: 3}], 0x03: [NamedInt(0x03, _("Cycle")), {LEDParam.period: 5, LEDParam.intensity: 7}], 0x08: [NamedInt(0x08, _("Boot")), {}], 0x09: [NamedInt(0x09, _("Demo")), {}], 0x0A: [ NamedInt(0x0A, _("Breathe")), {LEDParam.color: 0, LEDParam.period: 3, LEDParam.form: 5, LEDParam.intensity: 6}, ], 0x0B: [NamedInt(0x0B, _("Ripple")), {LEDParam.color: 0, LEDParam.period: 4}], 0x0E: [NamedInt(0x0E, _("Decomposition")), {LEDParam.period: 6, LEDParam.intensity: 8}], 0x0F: [NamedInt(0x0F, _("Signature1")), {LEDParam.period: 5, LEDParam.intensity: 7}], 0x10: [NamedInt(0x10, _("Signature2")), {LEDParam.period: 5, LEDParam.intensity: 7}], 0x15: [NamedInt(0x15, _("CycleS")), {LEDParam.saturation: 1, LEDParam.period: 6, LEDParam.intensity: 8}], } class LEDEffectSetting: # an effect plus its parameters def __init__(self, **kwargs): self.ID = None for key, val in kwargs.items(): setattr(self, key, val) @classmethod def from_bytes(cls, bytes, options=None): ID = next((ze.ID for ze in options if ze.index == bytes[0]), None) if options is not None else bytes[0] effect = LEDEffects[ID] if ID in LEDEffects else None args = {"ID": effect[0] if effect else None} if effect: for p, b in effect[1].items(): args[str(p)] = common.bytes2int(bytes[1 + b : 1 + b + LEDParamSize[p]]) else: args["bytes"] = bytes return cls(**args) def to_bytes(self, options=None): ID = self.ID if ID is None: return self.bytes if hasattr(self, "bytes") else b"\xff" * 11 else: bs = [0] * 10 for p, b in LEDEffects[ID][1].items(): bs[b : b + LEDParamSize[p]] = common.int2bytes(getattr(self, str(p), 0), LEDParamSize[p]) if options is not None: ID = next((ze.index for ze in options if ze.ID == ID), None) result = common.int2bytes(ID, 1) + bytes(bs) return result @classmethod def from_yaml(cls, loader, node): return cls(**loader.construct_mapping(node)) @classmethod def to_yaml(cls, dumper, data): return dumper.represent_mapping("!LEDEffectSetting", data.__dict__, flow_style=True) def __eq__(self, other): return isinstance(other, self.__class__) and self.to_bytes() == other.to_bytes() def __str__(self): return yaml.dump(self, width=float("inf")).rstrip("\n") yaml.SafeLoader.add_constructor("!LEDEffectSetting", LEDEffectSetting.from_yaml) yaml.add_representer(LEDEffectSetting, LEDEffectSetting.to_yaml) class LEDEffectInfo: # an effect that a zone can do def __init__(self, feature, function, device, zindex, eindex): info = device.feature_request(feature, function, zindex, eindex, 0x00) self.zindex, self.index, self.ID, self.capabilities, self.period = struct.unpack("!BBHHH", info[0:8]) def __str__(self): return f"LEDEffectInfo({self.zindex}, {self.index}, {self.ID}, {self.capabilities: x}, {self.period})" LEDZoneLocations = common.NamedInts() LEDZoneLocations[0x00] = _("Unknown Location") LEDZoneLocations[0x01] = _("Primary") LEDZoneLocations[0x02] = _("Logo") LEDZoneLocations[0x03] = _("Left Side") LEDZoneLocations[0x04] = _("Right Side") LEDZoneLocations[0x05] = _("Combined") LEDZoneLocations[0x06] = _("Primary 1") LEDZoneLocations[0x07] = _("Primary 2") LEDZoneLocations[0x08] = _("Primary 3") LEDZoneLocations[0x09] = _("Primary 4") LEDZoneLocations[0x0A] = _("Primary 5") LEDZoneLocations[0x0B] = _("Primary 6") class LEDZoneInfo: # effects that a zone can do def __init__(self, feature, function, offset, effect_function, device, index): info = device.feature_request(feature, function, index, 0xFF, 0x00) self.location, self.count = struct.unpack("!HB", info[1 + offset : 4 + offset]) self.index = index self.location = LEDZoneLocations[self.location] if LEDZoneLocations[self.location] else self.location self.effects = [] for i in range(0, self.count): self.effects.append(LEDEffectInfo(feature, effect_function, device, index, i)) def to_command(self, setting): for i in range(0, len(self.effects)): e = self.effects[i] if e.ID == setting.ID: return common.int2bytes(self.index, 1) + common.int2bytes(i, 1) + setting.to_bytes()[1:] return None def __str__(self): return f"LEDZoneInfo({self.index}, {self.location}, {[str(z) for z in self.effects]}" class LEDEffectsInfo: # effects that the LEDs can do, using COLOR_LED_EFFECTS def __init__(self, device): self.device = device info = device.feature_request(SupportedFeature.COLOR_LED_EFFECTS, 0x00) self.count, _, capabilities = struct.unpack("!BHH", info[0:5]) self.readable = capabilities & 0x1 self.zones = [] for i in range(0, self.count): self.zones.append(LEDZoneInfo(SupportedFeature.COLOR_LED_EFFECTS, 0x10, 0, 0x20, device, i)) def to_command(self, index, setting): return self.zones[index].to_command(setting) def __str__(self): zones = "\n".join([str(z) for z in self.zones]) return f"LEDEffectsInfo({self.device}, readable {self.readable}\n{zones})" class RGBEffectsInfo(LEDEffectsInfo): # effects that the LEDs can do using RGB_EFFECTS def __init__(self, device): self.device = device info = device.feature_request(SupportedFeature.RGB_EFFECTS, 0x00, 0xFF, 0xFF, 0x00) _, _, self.count, _, capabilities = struct.unpack("!BBBHH", info[0:7]) self.readable = capabilities & 0x1 self.zones = [] for i in range(0, self.count): self.zones.append(LEDZoneInfo(SupportedFeature.RGB_EFFECTS, 0x00, 1, 0x00, device, i)) ButtonBehaviors = common.NamedInts(MacroExecute=0x0, MacroStop=0x1, MacroStopAll=0x2, Send=0x8, Function=0x9) ButtonMappingTypes = common.NamedInts(No_Action=0x0, Button=0x1, Modifier_And_Key=0x2, Consumer_Key=0x3) ButtonFunctions = common.NamedInts( No_Action=0x0, Tilt_Left=0x1, Tilt_Right=0x2, Next_DPI=0x3, Previous_DPI=0x4, Cycle_DPI=0x5, Default_DPI=0x6, Shift_DPI=0x7, Next_Profile=0x8, Previous_Profile=0x9, Cycle_Profile=0xA, G_Shift=0xB, Battery_Status=0xC, Profile_Select=0xD, Mode_Switch=0xE, Host_Button=0xF, Scroll_Down=0x10, Scroll_Up=0x11, ) ButtonButtons = special_keys.MOUSE_BUTTONS ButtonModifiers = special_keys.modifiers ButtonKeys = special_keys.USB_HID_KEYCODES ButtonConsumerKeys = special_keys.HID_CONSUMERCODES class Button: """A button mapping""" def __init__(self, **kwargs): self.behavior = None for key, val in kwargs.items(): setattr(self, key, val) @classmethod def from_yaml(cls, loader, node): args = loader.construct_mapping(node) return cls(**args) @classmethod def to_yaml(cls, dumper, data): return dumper.represent_mapping("!Button", data.__dict__, flow_style=True) @classmethod def from_bytes(cls, bytes): behavior = ButtonBehaviors[bytes[0] >> 4] if behavior == ButtonBehaviors.MacroExecute or behavior == ButtonBehaviors.MacroStop: sector = ((bytes[0] & 0x0F) << 8) + bytes[1] address = (bytes[2] << 8) + bytes[3] result = cls(behavior=behavior, sector=sector, address=address) elif behavior == ButtonBehaviors.Send: mapping_type = ButtonMappingTypes[bytes[1]] if mapping_type == ButtonMappingTypes.Button: value = ButtonButtons[(bytes[2] << 8) + bytes[3]] result = cls(behavior=behavior, type=mapping_type, value=value) elif mapping_type == ButtonMappingTypes.Modifier_And_Key: modifiers = bytes[2] value = ButtonKeys[bytes[3]] result = cls(behavior=behavior, type=mapping_type, modifiers=modifiers, value=value) elif mapping_type == ButtonMappingTypes.Consumer_Key: value = ButtonConsumerKeys[(bytes[2] << 8) + bytes[3]] result = cls(behavior=behavior, type=mapping_type, value=value) elif mapping_type == ButtonMappingTypes.No_Action: result = cls(behavior=behavior, type=mapping_type) elif behavior == ButtonBehaviors.Function: value = ButtonFunctions[bytes[1]] if ButtonFunctions[bytes[1]] is not None else bytes[1] data = bytes[3] result = cls(behavior=behavior, value=value, data=data) else: result = cls(behavior=bytes[0] >> 4, bytes=bytes) return result def to_bytes(self): bytes = common.int2bytes(self.behavior << 4, 1) if self.behavior is not None else None if self.behavior == ButtonBehaviors.MacroExecute or self.behavior == ButtonBehaviors.MacroStop: bytes = common.int2bytes((self.behavior << 12) + self.sector, 2) + common.int2bytes(self.address, 2) elif self.behavior == ButtonBehaviors.Send: bytes += common.int2bytes(self.type, 1) if self.type == ButtonMappingTypes.Button: bytes += common.int2bytes(self.value, 2) elif self.type == ButtonMappingTypes.Modifier_And_Key: bytes += common.int2bytes(self.modifiers, 1) bytes += common.int2bytes(self.value, 1) elif self.type == ButtonMappingTypes.Consumer_Key: bytes += common.int2bytes(self.value, 2) elif self.type == ButtonMappingTypes.No_Action: bytes += b"\xff\xff" elif self.behavior == ButtonBehaviors.Function: data = common.int2bytes(self.data, 1) if self.data else b"\x00" bytes += common.int2bytes(self.value, 1) + b"\xff" + data else: bytes = self.bytes if self.bytes else b"\xff\xff\xff\xff" return bytes def __repr__(self): return "%s{%s}" % ( self.__class__.__name__, ", ".join([str(key) + ":" + str(val) for key, val in self.__dict__.items()]), ) yaml.SafeLoader.add_constructor("!Button", Button.from_yaml) yaml.add_representer(Button, Button.to_yaml) class OnboardProfile: """A single onboard profile""" def __init__(self, **kwargs): for key, val in kwargs.items(): setattr(self, key, val) @classmethod def from_yaml(cls, loader, node): args = loader.construct_mapping(node) return cls(**args) @classmethod def to_yaml(cls, dumper, data): return dumper.represent_mapping("!OnboardProfile", data.__dict__) @classmethod def from_bytes(cls, sector, enabled, buttons, gbuttons, bytes): return cls( sector=sector, enabled=enabled, report_rate=bytes[0], resolution_default_index=bytes[1], resolution_shift_index=bytes[2], resolutions=[struct.unpack("<H", bytes[i * 2 + 3 : i * 2 + 5])[0] for i in range(0, 5)], red=bytes[13], green=bytes[14], blue=bytes[15], power_mode=bytes[16], angle_snap=bytes[17], write_count=struct.unpack("<H", bytes[18:20])[0], reserved=bytes[20:28], ps_timeout=struct.unpack("<H", bytes[28:30])[0], po_timeout=struct.unpack("<H", bytes[30:32])[0], buttons=[Button.from_bytes(bytes[32 + i * 4 : 32 + i * 4 + 4]) for i in range(0, buttons)], gbuttons=[Button.from_bytes(bytes[96 + i * 4 : 96 + i * 4 + 4]) for i in range(0, gbuttons)], name=bytes[160:208].decode("utf-16le").rstrip("\x00").rstrip("\uffff"), lighting=[LEDEffectSetting.from_bytes(bytes[208 + i * 11 : 219 + i * 11]) for i in range(0, 4)], ) @classmethod def from_dev(cls, dev, i, sector, s, enabled, buttons, gbuttons): bytes = OnboardProfiles.read_sector(dev, sector, s) return cls.from_bytes(sector, enabled, buttons, gbuttons, bytes) def to_bytes(self, length): bytes = common.int2bytes(self.report_rate, 1) bytes += common.int2bytes(self.resolution_default_index, 1) + common.int2bytes(self.resolution_shift_index, 1) bytes += b"".join([self.resolutions[i].to_bytes(2, "little") for i in range(0, 5)]) bytes += common.int2bytes(self.red, 1) + common.int2bytes(self.green, 1) + common.int2bytes(self.blue, 1) bytes += common.int2bytes(self.power_mode, 1) + common.int2bytes(self.angle_snap, 1) bytes += self.write_count.to_bytes(2, "little") + self.reserved bytes += self.ps_timeout.to_bytes(2, "little") + self.po_timeout.to_bytes(2, "little") for i in range(0, 16): bytes += self.buttons[i].to_bytes() if i < len(self.buttons) else b"\xff\xff\xff\xff" for i in range(0, 16): bytes += self.gbuttons[i].to_bytes() if i < len(self.gbuttons) else b"\xff\xff\xff\xff" if self.name == "": bytes += b"\xff" * 48 else: bytes += self.name[0:24].ljust(24, "\x00").encode("utf-16le") for i in range(0, 4): bytes += self.lighting[i].to_bytes() while len(bytes) < length - 2: bytes += b"\xff" bytes += common.int2bytes(common.crc16(bytes), 2) return bytes def dump(self): print(f" Onboard Profile: {self.name}") print(f" Report Rate {self.report_rate} ms") print(f" DPI Resolutions {self.resolutions}") print(f" Default Resolution Index {self.res_index}, Shift Resolution Index {self.res_shift_index}") print(f" Colors {self.red} {self.green} {self.blue}") print(f" Power {self.power_mode}, Angle Snapping {self.angle_snap}") for i in range(0, len(self.buttons)): if self.buttons[i].behavior is not None: print(" BUTTON", i + 1, self.buttons[i]) for i in range(0, len(self.gbuttons)): if self.gbuttons[i].behavior is not None: print(" G-BUTTON", i + 1, self.gbuttons[i]) yaml.SafeLoader.add_constructor("!OnboardProfile", OnboardProfile.from_yaml) yaml.add_representer(OnboardProfile, OnboardProfile.to_yaml) OnboardProfilesVersion = 3 # Doesn't handle macros class OnboardProfiles: """The entire onboard profiles information""" def __init__(self, **kwargs): for key, val in kwargs.items(): setattr(self, key, val) @classmethod def from_yaml(cls, loader, node): args = loader.construct_mapping(node) return cls(**args) @classmethod def to_yaml(cls, dumper, data): return dumper.represent_mapping("!OnboardProfiles", data.__dict__) @classmethod def get_profile_headers(cls, device): i = 0 headers = [] chunk = device.feature_request(SupportedFeature.ONBOARD_PROFILES, 0x50, 0, 0, 0, i) s = 0x00 if chunk[0:4] == b"\x00\x00\x00\x00" or chunk[0:4] == b"\xff\xff\xff\xff": # look in ROM instead chunk = device.feature_request(SupportedFeature.ONBOARD_PROFILES, 0x50, 0x01, 0, 0, i) s = 0x01 while chunk[0:2] != b"\xff\xff": sector, enabled = struct.unpack("!HB", chunk[0:3]) headers.append((sector, enabled)) i += 1 chunk = device.feature_request(SupportedFeature.ONBOARD_PROFILES, 0x50, s, 0, 0, i * 4) return headers @classmethod def from_device(cls, device): if not device.online: # wake the device up if necessary device.ping() response = device.feature_request(SupportedFeature.ONBOARD_PROFILES, 0x00) memory, profile, _macro = struct.unpack("!BBB", response[0:3]) if memory != 0x01 or profile > 0x04: return count, oob, buttons, sectors, size, shift = struct.unpack("!BBBBHB", response[3:10]) gbuttons = buttons if (shift & 0x3 == 0x2) else 0 headers = OnboardProfiles.get_profile_headers(device) profiles = {} i = 0 for sector, enabled in headers: profiles[i + 1] = OnboardProfile.from_dev(device, i, sector, size, enabled, buttons, gbuttons) i += 1 return cls( version=OnboardProfilesVersion, name=device.name, count=count, buttons=buttons, gbuttons=gbuttons, sectors=sectors, size=size, profiles=profiles, ) def to_bytes(self): bytes = b"" for i in range(1, len(self.profiles) + 1): profiles_sector = common.int2bytes(self.profiles[i].sector, 2) profiles_enabled = common.int2bytes(self.profiles[i].enabled, 1) bytes += profiles_sector + profiles_enabled + b"\x00" bytes += b"\xff\xff\x00\x00" # marker after last profile while len(bytes) < self.size - 2: # leave room for CRC bytes += b"\xff" bytes += common.int2bytes(common.crc16(bytes), 2) return bytes @classmethod def read_sector(cls, dev, sector, s): # doesn't check for valid sector or size bytes = b"" o = 0 while o < s - 15: chunk = dev.feature_request(SupportedFeature.ONBOARD_PROFILES, 0x50, sector >> 8, sector & 0xFF, o >> 8, o & 0xFF) bytes += chunk o += 16 chunk = dev.feature_request( SupportedFeature.ONBOARD_PROFILES, 0x50, sector >> 8, sector & 0xFF, (s - 16) >> 8, (s - 16) & 0xFF, ) bytes += chunk[16 + o - s :] # the last chunk has to be read in an awkward way return bytes @classmethod def write_sector(cls, device, s, bs): # doesn't check for valid sector or size rbs = OnboardProfiles.read_sector(device, s, len(bs)) if rbs[:-2] == bs[:-2]: return False device.feature_request(SupportedFeature.ONBOARD_PROFILES, 0x60, s >> 8, s & 0xFF, 0, 0, len(bs) >> 8, len(bs) & 0xFF) o = 0 while o < len(bs) - 1: device.feature_request(SupportedFeature.ONBOARD_PROFILES, 0x70, bs[o : o + 16]) o += 16 device.feature_request(SupportedFeature.ONBOARD_PROFILES, 0x80) return True def write(self, device): try: written = 1 if OnboardProfiles.write_sector(device, 0, self.to_bytes()) else 0 except Exception as e: logger.warning("Exception writing onboard profile control sector") raise e for p in self.profiles.values(): try: if p.sector >= self.sectors: raise Exception(f"Sector {p.sector} not a writable sector") written += 1 if OnboardProfiles.write_sector(device, p.sector, p.to_bytes(self.size)) else 0 except Exception as e: logger.warning(f"Exception writing onboard profile sector {p.sector}") raise e return written def show(self): print(yaml.dump(self)) yaml.SafeLoader.add_constructor("!OnboardProfiles", OnboardProfiles.from_yaml) yaml.add_representer(OnboardProfiles, OnboardProfiles.to_yaml) def feature_request(device, feature, function=0x00, *params, no_reply=False): if device.online and device.features: if feature in device.features: feature_index = device.features[feature] return device.request((feature_index << 8) + (function & 0xFF), *params, no_reply=no_reply) # voltage to remaining charge from Logitech battery_voltage_remaining = ( (4186, 100), (4067, 90), (3989, 80), (3922, 70), (3859, 60), (3811, 50), (3778, 40), (3751, 30), (3717, 20), (3671, 10), (3646, 5), (3579, 2), (3500, 0), (-1000, 0), ) class Hidpp20: def get_firmware(self, device) -> tuple[common.FirmwareInfo] | None: """Reads a device's firmware info. :returns: a list of FirmwareInfo tuples, ordered by firmware layer. """ count = device.feature_request(SupportedFeature.DEVICE_FW_VERSION) if count: count = ord(count[:1]) fw = [] for index in range(0, count): fw_info = device.feature_request(SupportedFeature.DEVICE_FW_VERSION, 0x10, index) if fw_info: level = ord(fw_info[:1]) & 0x0F if level == 0 or level == 1: name, version_major, version_minor, build = struct.unpack("!3sBBH", fw_info[1:8]) version = f"{version_major:02X}.{version_minor:02X}" if build: version += f".B{build:04X}" extras = fw_info[9:].rstrip(b"\x00") or None fw_info = common.FirmwareInfo(FirmwareKind(level), name.decode("ascii"), version, extras) elif level == FirmwareKind.Hardware: fw_info = common.FirmwareInfo(FirmwareKind.Hardware, "", str(ord(fw_info[1:2])), None) else: fw_info = common.FirmwareInfo(FirmwareKind.Other, "", "", None) fw.append(fw_info) return tuple(fw) def get_ids(self, device): """Reads a device's ids (unit and model numbers)""" ids = device.feature_request(SupportedFeature.DEVICE_FW_VERSION) if ids: unitId = ids[1:5] modelId = ids[7:13] transport_bits = ord(ids[6:7]) offset = 0 tid_map = {} for transport, flag in [("btid", 0x1), ("btleid", 0x02), ("wpid", 0x04), ("usbid", 0x08)]: if transport_bits & flag: tid_map[transport] = modelId[offset : offset + 2].hex().upper() offset = offset + 2 return unitId.hex().upper(), modelId.hex().upper(), tid_map def get_kind(self, device: Device): """Reads a device's type. :see DEVICE_KIND: :returns: a string describing the device type, or ``None`` if the device is not available or does not support the ``DEVICE_NAME`` feature. """ kind = device.feature_request(SupportedFeature.DEVICE_NAME, 0x20) if kind: kind = ord(kind[:1]) try: return KIND_MAP[DEVICE_KIND[kind]] except Exception: return None def get_name(self, device: Device): """Reads a device's name. :returns: a string with the device name, or ``None`` if the device is not available or does not support the ``DEVICE_NAME`` feature. """ name_length = device.feature_request(SupportedFeature.DEVICE_NAME) if name_length: name_length = ord(name_length[:1]) name = b"" while len(name) < name_length: fragment = device.feature_request(SupportedFeature.DEVICE_NAME, 0x10, len(name)) if fragment: name += fragment[: name_length - len(name)] else: logger.error("failed to read whole name of %s (expected %d chars)", device, name_length) return None return name.decode("utf-8") def get_friendly_name(self, device: Device): """Reads a device's friendly name. :returns: a string with the device name, or ``None`` if the device is not available or does not support the ``DEVICE_NAME`` feature. """ name_length = device.feature_request(SupportedFeature.DEVICE_FRIENDLY_NAME) if name_length: name_length = ord(name_length[:1]) name = b"" while len(name) < name_length: fragment = device.feature_request(SupportedFeature.DEVICE_FRIENDLY_NAME, 0x10, len(name)) if fragment: name += fragment[1 : name_length - len(name) + 1] else: logger.error("failed to read whole name of %s (expected %d chars)", device, name_length) return None return name.decode("utf-8") def get_battery_status(self, device: Device): report = device.feature_request(SupportedFeature.BATTERY_STATUS) if report: return decipher_battery_status(report) def get_battery_unified(self, device: Device): report = device.feature_request(SupportedFeature.UNIFIED_BATTERY, 0x10) if report is not None: return decipher_battery_unified(report) def get_battery_voltage(self, device: Device): report = device.feature_request(SupportedFeature.BATTERY_VOLTAGE) if report is not None: return decipher_battery_voltage(report) def get_adc_measurement(self, device: Device): try: # this feature call produces an error for headsets that are connected but inactive report = device.feature_request(SupportedFeature.ADC_MEASUREMENT) if report is not None: return decipher_adc_measurement(report) except exceptions.FeatureCallError: return SupportedFeature.ADC_MEASUREMENT if SupportedFeature.ADC_MEASUREMENT in device.features else None def get_battery(self, device, feature): """Return battery information - feature, approximate level, next, charging, voltage or battery feature if there is one but it is not responding or None for no battery feature""" if feature is not None: battery_function = battery_functions.get(feature, None) if battery_function: result = battery_function(self, device) if result: return result else: for battery_function in battery_functions.values(): result = battery_function(self, device) if result: return result return 0 def get_keys(self, device: Device): # TODO: add here additional variants for other REPROG_CONTROLS count = None if SupportedFeature.REPROG_CONTROLS_V2 in device.features: count = device.feature_request(SupportedFeature.REPROG_CONTROLS_V2) return KeysArrayV2(device, ord(count[:1])) elif SupportedFeature.REPROG_CONTROLS_V4 in device.features: count = device.feature_request(SupportedFeature.REPROG_CONTROLS_V4) return KeysArrayV4(device, ord(count[:1])) return None def get_remap_keys(self, device: Device): count = device.feature_request(SupportedFeature.PERSISTENT_REMAPPABLE_ACTION, 0x10) if count: return KeysArrayPersistent(device, ord(count[:1])) def get_gestures(self, device: Device): if getattr(device, "_gestures", None) is not None: return device._gestures if SupportedFeature.GESTURE_2 in device.features: return Gestures(device) def get_backlight(self, device: Device): if getattr(device, "_backlight", None) is not None: return device._backlight if SupportedFeature.BACKLIGHT2 in device.features: return Backlight(device) def get_profiles(self, device: Device): if getattr(device, "_profiles", None) is not None: return device._profiles if SupportedFeature.ONBOARD_PROFILES in device.features: return OnboardProfiles.from_device(device) def get_mouse_pointer_info(self, device: Device): pointer_info = device.feature_request(SupportedFeature.MOUSE_POINTER) if pointer_info: dpi, flags = struct.unpack("!HB", pointer_info[:3]) acceleration = ("none", "low", "med", "high")[flags & 0x3] suggest_os_ballistics = (flags & 0x04) != 0 suggest_vertical_orientation = (flags & 0x08) != 0 return { "dpi": dpi, "acceleration": acceleration, "suggest_os_ballistics": suggest_os_ballistics, "suggest_vertical_orientation": suggest_vertical_orientation, } def get_vertical_scrolling_info(self, device: Device): vertical_scrolling_info = device.feature_request(SupportedFeature.VERTICAL_SCROLLING) if vertical_scrolling_info: roller, ratchet, lines = struct.unpack("!BBB", vertical_scrolling_info[:3]) roller_type = ( "reserved", "standard", "reserved", "3G", "micro", "normal touch pad", "inverted touch pad", "reserved", )[roller] return {"roller": roller_type, "ratchet": ratchet, "lines": lines} def get_hi_res_scrolling_info(self, device: Device): hi_res_scrolling_info = device.feature_request(SupportedFeature.HI_RES_SCROLLING) if hi_res_scrolling_info: mode, resolution = struct.unpack("!BB", hi_res_scrolling_info[:2]) return mode, resolution def get_pointer_speed_info(self, device: Device): pointer_speed_info = device.feature_request(SupportedFeature.POINTER_SPEED) if pointer_speed_info: pointer_speed_hi, pointer_speed_lo = struct.unpack("!BB", pointer_speed_info[:2]) # if pointer_speed_lo > 0: # pointer_speed_lo = pointer_speed_lo return pointer_speed_hi + pointer_speed_lo / 256 def get_lowres_wheel_status(self, device: Device): lowres_wheel_status = device.feature_request(SupportedFeature.LOWRES_WHEEL) if lowres_wheel_status: wheel_flag = struct.unpack("!B", lowres_wheel_status[:1])[0] wheel_reporting = ("HID", "HID++")[wheel_flag & 0x01] return wheel_reporting def get_hires_wheel(self, device: Device): caps = device.feature_request(SupportedFeature.HIRES_WHEEL, 0x00) mode = device.feature_request(SupportedFeature.HIRES_WHEEL, 0x10) ratchet = device.feature_request(SupportedFeature.HIRES_WHEEL, 0x030) if caps and mode and ratchet: # Parse caps multi, flags = struct.unpack("!BB", caps[:2]) has_invert = (flags & 0x08) != 0 has_ratchet = (flags & 0x04) != 0 # Parse mode wheel_mode, reserved = struct.unpack("!BB", mode[:2]) target = (wheel_mode & 0x01) != 0 res = (wheel_mode & 0x02) != 0 inv = (wheel_mode & 0x04) != 0 # Parse Ratchet switch ratchet_mode, reserved = struct.unpack("!BB", ratchet[:2]) ratchet = (ratchet_mode & 0x01) != 0 return multi, has_invert, has_ratchet, inv, res, target, ratchet def get_new_fn_inversion(self, device: Device): state = device.feature_request(SupportedFeature.NEW_FN_INVERSION, 0x00) if state: inverted, default_inverted = struct.unpack("!BB", state[:2]) inverted = (inverted & 0x01) != 0 default_inverted = (default_inverted & 0x01) != 0 return inverted, default_inverted def get_host_names(self, device: Device): state = device.feature_request(SupportedFeature.HOSTS_INFO, 0x00) host_names = {} if state: capability_flags, _ignore, numHosts, currentHost = struct.unpack("!BBBB", state[:4]) if capability_flags & 0x01: # device can get host names for host in range(0, numHosts): hostinfo = device.feature_request(SupportedFeature.HOSTS_INFO, 0x10, host) _ignore, status, _ignore, _ignore, nameLen, _ignore = struct.unpack("!BBBBBB", hostinfo[:6]) name = "" remaining = nameLen while remaining > 0: name_piece = device.feature_request(SupportedFeature.HOSTS_INFO, 0x30, host, nameLen - remaining) if name_piece: name += name_piece[2 : 2 + min(remaining, 14)].decode() remaining = max(0, remaining - 14) else: remaining = 0 host_names[host] = (bool(status), name) if host_names: # update the current host's name if it doesn't match the system name hostname = socket.gethostname().partition(".")[0] if host_names[currentHost][1] != hostname: self.set_host_name(device, hostname, host_names[currentHost][1]) host_names[currentHost] = (host_names[currentHost][0], hostname) return host_names def set_host_name(self, device: Device, name, currentName=""): name = bytearray(name, "utf-8") currentName = bytearray(currentName, "utf-8") if logger.isEnabledFor(logging.INFO): logger.info("Setting host name to %s", name) state = device.feature_request(SupportedFeature.HOSTS_INFO, 0x00) if state: flags, _ignore, _ignore, currentHost = struct.unpack("!BBBB", state[:4]) if flags & 0x02: hostinfo = device.feature_request(SupportedFeature.HOSTS_INFO, 0x10, currentHost) _ignore, _ignore, _ignore, _ignore, _ignore, maxNameLen = struct.unpack("!BBBBBB", hostinfo[:6]) if name[:maxNameLen] == currentName[:maxNameLen] and False: return True length = min(maxNameLen, len(name)) chunk = 0 while chunk < length: response = device.feature_request( SupportedFeature.HOSTS_INFO, 0x40, currentHost, chunk, name[chunk : chunk + 14] ) if not response: return False chunk += 14 return True def get_onboard_mode(self, device: Device): state = device.feature_request(SupportedFeature.ONBOARD_PROFILES, 0x20) if state: mode = struct.unpack("!B", state[:1])[0] return mode def set_onboard_mode(self, device: Device, mode): state = device.feature_request(SupportedFeature.ONBOARD_PROFILES, 0x10, mode) return state def get_polling_rate(self, device: Device): state = device.feature_request(SupportedFeature.REPORT_RATE, 0x10) if state: rate = struct.unpack("!B", state[:1])[0] return str(rate) + "ms" else: rates = ["8ms", "4ms", "2ms", "1ms", "500us", "250us", "125us"] state = device.feature_request(SupportedFeature.EXTENDED_ADJUSTABLE_REPORT_RATE, 0x20) if state: rate = struct.unpack("!B", state[:1])[0] return rates[rate] def get_remaining_pairing(self, device: Device): result = device.feature_request(SupportedFeature.REMAINING_PAIRING, 0x0) if result: result = struct.unpack("!B", result[:1])[0] SupportedFeature._fallback = lambda x: f"unknown:{x:04X}" return result def config_change(self, device: Device, configuration, no_reply=False): return device.feature_request(SupportedFeature.CONFIG_CHANGE, 0x10, configuration, no_reply=no_reply) battery_functions = { SupportedFeature.BATTERY_STATUS: Hidpp20.get_battery_status, SupportedFeature.BATTERY_VOLTAGE: Hidpp20.get_battery_voltage, SupportedFeature.UNIFIED_BATTERY: Hidpp20.get_battery_unified, SupportedFeature.ADC_MEASUREMENT: Hidpp20.get_adc_measurement, } def decipher_battery_status(report: FixedBytes5) -> Tuple[Any, Battery]: battery_discharge_level, battery_discharge_next_level, battery_status = struct.unpack("!BBB", report[:3]) if battery_discharge_level == 0: battery_discharge_level = None try: status = BatteryStatus(battery_status) except ValueError: status = None logger.debug(f"Unknown battery status byte 0x{battery_status:02X}") if logger.isEnabledFor(logging.DEBUG): logger.debug( "battery status %s%% charged, next %s%%, status %s", battery_discharge_level, battery_discharge_next_level, status ) return SupportedFeature.BATTERY_STATUS, Battery(battery_discharge_level, battery_discharge_next_level, status, None) def decipher_battery_voltage(report): voltage, flags = struct.unpack(">HB", report[:3]) status = BatteryStatus.DISCHARGING charge_sts = ERROR.unknown charge_lvl = CHARGE_LEVEL.average charge_type = CHARGE_TYPE.standard if flags & (1 << 7): status = BatteryStatus.RECHARGING charge_sts = CHARGE_STATUS[flags & 0x03] if charge_sts is None: charge_sts = ERROR.unknown elif charge_sts == CHARGE_STATUS.full: charge_lvl = CHARGE_LEVEL.full status = BatteryStatus.FULL if flags & (1 << 3): charge_type = CHARGE_TYPE.fast elif flags & (1 << 4): charge_type = CHARGE_TYPE.slow status = BatteryStatus.SLOW_RECHARGE elif flags & (1 << 5): charge_lvl = CHARGE_LEVEL.critical for level in battery_voltage_remaining: if level[0] < voltage: charge_lvl = level[1] break if logger.isEnabledFor(logging.DEBUG): logger.debug( "battery voltage %d mV, charging %s, status %d = %s, level %s, type %s", voltage, status, (flags & 0x03), charge_sts, charge_lvl, charge_type, ) return SupportedFeature.BATTERY_VOLTAGE, Battery(charge_lvl, None, status, voltage) def decipher_battery_unified(report): discharge, level, status_byte, _ignore = struct.unpack("!BBBB", report[:4]) try: status = BatteryStatus(status_byte) except ValueError: status = None logger.debug(f"Unknown battery status byte 0x{status_byte:02X}") if logger.isEnabledFor(logging.DEBUG): logger.debug("battery unified %s%% charged, level %s, charging %s", discharge, level, status) if level == 8: level = BatteryLevelApproximation.FULL elif level == 4: level = BatteryLevelApproximation.GOOD elif level == 2: level = BatteryLevelApproximation.LOW elif level == 1: level = BatteryLevelApproximation.CRITICAL else: level = BatteryLevelApproximation.EMPTY return SupportedFeature.UNIFIED_BATTERY, Battery(discharge if discharge else level, None, status, None) def decipher_adc_measurement(report): # partial implementation - needs mapping to levels charge_level = None adc, flags = struct.unpack("!HB", report[:3]) for level in battery_voltage_remaining: if level[0] < adc: charge_level = level[1] break if flags & 0x01: status = BatteryStatus.RECHARGING if flags & 0x02 else BatteryStatus.DISCHARGING return SupportedFeature.ADC_MEASUREMENT, Battery(charge_level, None, status, adc)
77,824
Python
.py
1,628
37.934275
126
0.618367
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,457
hidpp20_constants.py
pwr-Solaar_Solaar/lib/logitech_receiver/hidpp20_constants.py
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/ ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from enum import IntEnum from enum import IntFlag from .common import NamedInts # <FeaturesSupported.xml sed '/LD_FID_/{s/.*LD_FID_/\t/;s/"[ \t]*Id="/=/;s/" \/>/,/p}' | sort -t= -k2 # additional features names taken from https://github.com/cvuchener/hidpp and # https://github.com/Logitech/cpg-docs/tree/master/hidpp20 """Possible features available on a Logitech device. A particular device might not support all these features, and may support other unknown features as well. """ class SupportedFeature(IntEnum): ROOT = 0x0000 FEATURE_SET = 0x0001 FEATURE_INFO = 0x0002 # Common DEVICE_FW_VERSION = 0x0003 DEVICE_UNIT_ID = 0x0004 DEVICE_NAME = 0x0005 DEVICE_GROUPS = 0x0006 DEVICE_FRIENDLY_NAME = 0x0007 KEEP_ALIVE = 0x0008 CONFIG_CHANGE = 0x0020 CRYPTO_ID = 0x0021 TARGET_SOFTWARE = 0x0030 WIRELESS_SIGNAL_STRENGTH = 0x0080 DFUCONTROL_LEGACY = 0x00C0 DFUCONTROL_UNSIGNED = 0x00C1 DFUCONTROL_SIGNED = 0x00C2 DFUCONTROL = 0x00C3 DFU = 0x00D0 BATTERY_STATUS = 0x1000 BATTERY_VOLTAGE = 0x1001 UNIFIED_BATTERY = 0x1004 CHARGING_CONTROL = 0x1010 LED_CONTROL = 0x1300 FORCE_PAIRING = 0x1500 GENERIC_TEST = 0x1800 DEVICE_RESET = 0x1802 OOBSTATE = 0x1805 CONFIG_DEVICE_PROPS = 0x1806 CHANGE_HOST = 0x1814 HOSTS_INFO = 0x1815 BACKLIGHT = 0x1981 BACKLIGHT2 = 0x1982 BACKLIGHT3 = 0x1983 ILLUMINATION = 0x1990 PRESENTER_CONTROL = 0x1A00 SENSOR_3D = 0x1A01 REPROG_CONTROLS = 0x1B00 REPROG_CONTROLS_V2 = 0x1B01 REPROG_CONTROLS_V2_2 = 0x1B02 # LogiOptions 2.10.73 features.xml REPROG_CONTROLS_V3 = 0x1B03 REPROG_CONTROLS_V4 = 0x1B04 REPORT_HID_USAGE = 0x1BC0 PERSISTENT_REMAPPABLE_ACTION = 0x1C00 WIRELESS_DEVICE_STATUS = 0x1D4B REMAINING_PAIRING = 0x1DF0 FIRMWARE_PROPERTIES = 0x1F1F ADC_MEASUREMENT = 0x1F20 # Mouse LEFT_RIGHT_SWAP = 0x2001 SWAP_BUTTON_CANCEL = 0x2005 POINTER_AXIS_ORIENTATION = 0x2006 VERTICAL_SCROLLING = 0x2100 SMART_SHIFT = 0x2110 SMART_SHIFT_ENHANCED = 0x2111 HI_RES_SCROLLING = 0x2120 HIRES_WHEEL = 0x2121 LOWRES_WHEEL = 0x2130 THUMB_WHEEL = 0x2150 MOUSE_POINTER = 0x2200 ADJUSTABLE_DPI = 0x2201 EXTENDED_ADJUSTABLE_DPI = 0x2202 POINTER_SPEED = 0x2205 ANGLE_SNAPPING = 0x2230 SURFACE_TUNING = 0x2240 XY_STATS = 0x2250 WHEEL_STATS = 0x2251 HYBRID_TRACKING = 0x2400 # Keyboard FN_INVERSION = 0x40A0 NEW_FN_INVERSION = 0x40A2 K375S_FN_INVERSION = 0x40A3 ENCRYPTION = 0x4100 LOCK_KEY_STATE = 0x4220 SOLAR_DASHBOARD = 0x4301 KEYBOARD_LAYOUT = 0x4520 KEYBOARD_DISABLE_KEYS = 0x4521 KEYBOARD_DISABLE_BY_USAGE = 0x4522 DUALPLATFORM = 0x4530 MULTIPLATFORM = 0x4531 KEYBOARD_LAYOUT_2 = 0x4540 CROWN = 0x4600 # Touchpad TOUCHPAD_FW_ITEMS = 0x6010 TOUCHPAD_SW_ITEMS = 0x6011 TOUCHPAD_WIN8_FW_ITEMS = 0x6012 TAP_ENABLE = 0x6020 TAP_ENABLE_EXTENDED = 0x6021 CURSOR_BALLISTIC = 0x6030 TOUCHPAD_RESOLUTION = 0x6040 TOUCHPAD_RAW_XY = 0x6100 TOUCHMOUSE_RAW_POINTS = 0x6110 TOUCHMOUSE_6120 = 0x6120 GESTURE = 0x6500 GESTURE_2 = 0x6501 # Gaming Devices GKEY = 0x8010 MKEYS = 0x8020 MR = 0x8030 BRIGHTNESS_CONTROL = 0x8040 REPORT_RATE = 0x8060 EXTENDED_ADJUSTABLE_REPORT_RATE = 0x8061 COLOR_LED_EFFECTS = 0x8070 RGB_EFFECTS = 0x8071 PER_KEY_LIGHTING = 0x8080 PER_KEY_LIGHTING_V2 = 0x8081 MODE_STATUS = 0x8090 ONBOARD_PROFILES = 0x8100 MOUSE_BUTTON_SPY = 0x8110 LATENCY_MONITORING = 0x8111 GAMING_ATTACHMENTS = 0x8120 FORCE_FEEDBACK = 0x8123 # Headsets SIDETONE = 0x8300 EQUALIZER = 0x8310 HEADSET_OUT = 0x8320 # Fake features for Solaar internal use MOUSE_GESTURE = 0xFE00 def __str__(self): return self.name.replace("_", " ") class FeatureFlag(IntFlag): """Single bit flags.""" INTERNAL = 0x20 HIDDEN = 0x40 OBSOLETE = 0x80 DEVICE_KIND = NamedInts( keyboard=0x00, remote_control=0x01, numpad=0x02, mouse=0x03, touchpad=0x04, trackball=0x05, presenter=0x06, receiver=0x07, ) ONBOARD_MODES = NamedInts(MODE_NO_CHANGE=0x00, MODE_ONBOARD=0x01, MODE_HOST=0x02) CHARGE_STATUS = NamedInts(charging=0x00, full=0x01, not_charging=0x02, error=0x07) CHARGE_LEVEL = NamedInts(average=50, full=90, critical=5) CHARGE_TYPE = NamedInts(standard=0x00, fast=0x01, slow=0x02) ERROR = NamedInts( unknown=0x01, invalid_argument=0x02, out_of_range=0x03, hardware_error=0x04, logitech_internal=0x05, invalid_feature_index=0x06, invalid_function=0x07, busy=0x08, unsupported=0x09, ) # Gesture Ids for feature GESTURE_2 GESTURE = NamedInts( Tap1Finger=1, # task Left_Click Tap2Finger=2, # task Right_Click Tap3Finger=3, Click1Finger=4, # task Left_Click Click2Finger=5, # task Right_Click Click3Finger=6, DoubleTap1Finger=10, DoubleTap2Finger=11, DoubleTap3Finger=12, Track1Finger=20, # action MovePointer TrackingAcceleration=21, TapDrag1Finger=30, # action Drag TapDrag2Finger=31, # action SecondaryDrag Drag3Finger=32, TapGestures=33, # group all tap gestures under a single UI setting FnClickGestureSuppression=34, # suppresses Tap and Edge gestures, toggled by Fn+Click Scroll1Finger=40, # action ScrollOrPageXY / ScrollHorizontal Scroll2Finger=41, # action ScrollOrPageXY / ScrollHorizontal Scroll2FingerHoriz=42, # action ScrollHorizontal Scroll2FingerVert=43, # action WheelScrolling Scroll2FingerStateless=44, NaturalScrolling=45, # affects native HID wheel reporting by gestures, not when diverted Thumbwheel=46, # action WheelScrolling VScrollInertia=48, VScrollBallistics=49, Swipe2FingerHoriz=50, # action PageScreen Swipe3FingerHoriz=51, # action PageScreen Swipe4FingerHoriz=52, # action PageScreen Swipe3FingerVert=53, Swipe4FingerVert=54, LeftEdgeSwipe1Finger=60, RightEdgeSwipe1Finger=61, BottomEdgeSwipe1Finger=62, TopEdgeSwipe1Finger=63, LeftEdgeSwipe1Finger2=64, # task HorzScrollNoRepeatSet RightEdgeSwipe1Finger2=65, # task 122 ?? BottomEdgeSwipe1Finger2=66, TopEdgeSwipe1Finger2=67, # task 121 ?? LeftEdgeSwipe2Finger=70, RightEdgeSwipe2Finger=71, BottomEdgeSwipe2Finger=72, TopEdgeSwipe2Finger=73, Zoom2Finger=80, # action Zoom Zoom2FingerPinch=81, # ZoomBtnInSet Zoom2FingerSpread=82, # ZoomBtnOutSet Zoom3Finger=83, Zoom2FingerStateless=84, # action Zoom TwoFingersPresent=85, Rotate2Finger=87, Finger1=90, Finger2=91, Finger3=92, Finger4=93, Finger5=94, Finger6=95, Finger7=96, Finger8=97, Finger9=98, Finger10=99, DeviceSpecificRawData=100, ) GESTURE._fallback = lambda x: f"unknown:{x:04X}" # Param Ids for feature GESTURE_2 PARAM = NamedInts( ExtraCapabilities=1, # not suitable for use PixelZone=2, # 4 2-byte integers, left, bottom, width, height; pixels RatioZone=3, # 4 bytes, left, bottom, width, height; unit 1/240 pad size ScaleFactor=4, # 2-byte integer, with 256 as normal scale ) PARAM._fallback = lambda x: f"unknown:{x:04X}"
8,155
Python
.py
249
28.365462
101
0.722201
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,458
settings.py
pwr-Solaar_Solaar/lib/logitech_receiver/settings.py
## Copyright (C) 2012-2013 Daniel Pavel ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from __future__ import annotations import logging import math import struct import time from solaar.i18n import _ from . import common from . import hidpp20_constants from .common import NamedInt from .common import NamedInts logger = logging.getLogger(__name__) SENSITIVITY_IGNORE = "ignore" KIND = NamedInts( toggle=0x01, choice=0x02, range=0x04, map_choice=0x0A, multiple_toggle=0x10, packed_range=0x20, multiple_range=0x40, hetero=0x80, ) def bool_or_toggle(current: bool | str, new: bool | str) -> bool: if isinstance(new, bool): return new try: return bool(int(new)) except (TypeError, ValueError): new = str(new).lower() if new in ("true", "yes", "on", "t", "y"): return True if new in ("false", "no", "off", "f", "n"): return False if new in ("~", "toggle"): return not current return None class Setting: """A setting descriptor. Needs to be instantiated for each specific device.""" name = label = description = "" feature = register = kind = None min_version = 0 persist = True rw_options = {} validator_class = None validator_options = {} def __init__(self, device, rw, validator): self._device = device self._rw = rw self._validator = validator self.kind = getattr(self._validator, "kind", None) self._value = None @classmethod def build(cls, device): assert cls.feature or cls.register, "Settings require either a feature or a register" rw_class = cls.rw_class if hasattr(cls, "rw_class") else FeatureRW if cls.feature else RegisterRW rw = rw_class(cls.feature if cls.feature else cls.register, **cls.rw_options) p = device.protocol if p == 1.0: # HID++ 1.0 devices do not support features assert rw.kind == RegisterRW.kind elif p >= 2.0: # HID++ 2.0 devices do not support registers assert rw.kind == FeatureRW.kind validator_class = cls.validator_class validator = validator_class.build(cls, device, **cls.validator_options) if validator: assert cls.kind is None or cls.kind & validator.kind != 0 return cls(device, rw, validator) def val_to_string(self, value): return self._validator.to_string(value) @property def choices(self): assert hasattr(self, "_value") assert hasattr(self, "_device") return self._validator.choices if self._validator and self._validator.kind & KIND.choice else None @property def range(self): assert hasattr(self, "_value") assert hasattr(self, "_device") if self._validator.kind == KIND.range: return self._validator.min_value, self._validator.max_value def _pre_read(self, cached, key=None): if self.persist and self._value is None and getattr(self._device, "persister", None): # We haven't read a value from the device yet, # maybe we have something in the configuration. self._value = self._device.persister.get(self.name) if cached and self._value is not None: if getattr(self._device, "persister", None) and self.name not in self._device.persister: # If this is a new device (or a new setting for an old device), # make sure to save its current value for the next time. self._device.persister[self.name] = self._value if self.persist else None def read(self, cached=True): assert hasattr(self, "_value") assert hasattr(self, "_device") self._pre_read(cached) if cached and self._value is not None: if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: cached value %r on %s", self.name, self._value, self._device) return self._value if self._device.online: reply = self._rw.read(self._device) if reply: self._value = self._validator.validate_read(reply) if self._value is not None and self._device.persister and self.name not in self._device.persister: # Don't update the persister if it already has a value, # otherwise the first read might overwrite the value we wanted. self._device.persister[self.name] = self._value if self.persist else None if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: read value %r on %s", self.name, self._value, self._device) return self._value def _pre_write(self, save=True): # Remember the value we're trying to set, even if the write fails. # This way even if the device is offline or some other error occurs, # the last value we've tried to write is remembered in the configuration. if self._device.persister and save: self._device.persister[self.name] = self._value if self.persist else None def update(self, value, save=True): self._value = value self._pre_write(save) def write(self, value, save=True): assert hasattr(self, "_value") assert hasattr(self, "_device") assert value is not None if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: write %r to %s", self.name, value, self._device) if self._device.online: if self._value != value: self.update(value, save) current_value = None if self._validator.needs_current_value: # the _validator needs the current value, possibly to merge flag values current_value = self._rw.read(self._device) if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: current value %r on %s", self.name, current_value, self._device) data_bytes = self._validator.prepare_write(value, current_value) if data_bytes is not None: if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: prepare write(%s) => %r", self.name, value, data_bytes) reply = self._rw.write(self._device, data_bytes) if not reply: # tell whomever is calling that the write failed return None return value def acceptable(self, args, current): return self._validator.acceptable(args, current) if self._validator else None def compare(self, args, current): return self._validator.compare(args, current) if self._validator else None def apply(self): assert hasattr(self, "_value") assert hasattr(self, "_device") if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: apply (%s)", self.name, self._device) try: value = self.read(self.persist) # Don't use persisted value if setting doesn't persist if self.persist and value is not None: # If setting doesn't persist no need to write value just read self.write(value, save=False) except Exception as e: if logger.isEnabledFor(logging.WARNING): logger.warning("%s: error applying %s so ignore it (%s): %s", self.name, self._value, self._device, repr(e)) def __str__(self): if hasattr(self, "_value"): assert hasattr(self, "_device") return "<Setting([%s:%s] %s:%s=%s)>" % ( self._rw.kind, self._validator.kind if self._validator else None, self._device.codename, self.name, self._value, ) return f"<Setting([{self._rw.kind}:{self._validator.kind if self._validator else None}] {self.name})>" __repr__ = __str__ class Settings(Setting): """A setting descriptor for multiple choices, being a map from keys to values. Needs to be instantiated for each specific device.""" def read(self, cached=True): assert hasattr(self, "_value") assert hasattr(self, "_device") if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: settings read %r from %s", self.name, self._value, self._device) self._pre_read(cached) if cached and self._value is not None: return self._value if self._device.online: reply_map = {} for key in self._validator.choices: reply = self._rw.read(self._device, key) if reply: reply_map[int(key)] = self._validator.validate_read(reply, key) self._value = reply_map if getattr(self._device, "persister", None) and self.name not in self._device.persister: # Don't update the persister if it already has a value, # otherwise the first read might overwrite the value we wanted. self._device.persister[self.name] = self._value if self.persist else None return self._value def read_key(self, key, cached=True): assert hasattr(self, "_value") assert hasattr(self, "_device") assert key is not None if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: settings read %r key %r from %s", self.name, self._value, key, self._device) self._pre_read(cached) if cached and self._value is not None: return self._value[int(key)] if self._device.online: reply = self._rw.read(self._device, key) if reply: self._value[int(key)] = self._validator.validate_read(reply, key) if getattr(self._device, "persister", None) and self.name not in self._device.persister: self._device.persister[self.name] = self._value if self.persist else None return self._value[int(key)] def write(self, map, save=True): assert hasattr(self, "_value") assert hasattr(self, "_device") assert map is not None if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: settings write %r to %s", self.name, map, self._device) if self._device.online: self.update(map, save) for key, value in map.items(): data_bytes = self._validator.prepare_write(int(key), value) if data_bytes is not None: if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: settings prepare map write(%s,%s) => %r", self.name, key, value, data_bytes) reply = self._rw.write(self._device, int(key), data_bytes) if not reply: return None return map def update_key_value(self, key, value, save=True): self._value[int(key)] = value self._pre_write(save) def write_key_value(self, key, value, save=True): assert hasattr(self, "_value") assert hasattr(self, "_device") assert key is not None assert value is not None if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: settings write key %r value %r to %s", self.name, key, value, self._device) if self._device.online: if not self._value: self.read() try: data_bytes = self._validator.prepare_write(int(key), value) # always need to write to configuration because dictionary is shared and could have changed self.update_key_value(key, value, save) except ValueError: data_bytes = value = None if data_bytes is not None: if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: settings prepare key value write(%s,%s) => %r", self.name, key, value, data_bytes) reply = self._rw.write(self._device, int(key), data_bytes) if not reply: return None return value class LongSettings(Setting): """A setting descriptor for multiple choices, being a map from keys to values. Allows multiple write requests, if the options don't fit in 16 bytes. The validator must return a list. Needs to be instantiated for each specific device.""" def read(self, cached=True): assert hasattr(self, "_value") assert hasattr(self, "_device") if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: settings read %r from %s", self.name, self._value, self._device) self._pre_read(cached) if cached and self._value is not None: return self._value if self._device.online: reply_map = {} # Reading one item at a time. This can probably be optimised for item in self._validator.items: r = self._validator.prepare_read_item(item) reply = self._rw.read(self._device, r) if reply: reply_map[int(item)] = self._validator.validate_read_item(reply, item) self._value = reply_map if getattr(self._device, "persister", None) and self.name not in self._device.persister: # Don't update the persister if it already has a value, # otherwise the first read might overwrite the value we wanted. self._device.persister[self.name] = self._value if self.persist else None return self._value def read_item(self, item, cached=True): assert hasattr(self, "_value") assert hasattr(self, "_device") assert item is not None if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: settings read %r item %r from %s", self.name, self._value, item, self._device) self._pre_read(cached) if cached and self._value is not None: return self._value[int(item)] if self._device.online: r = self._validator.prepare_read_item(item) reply = self._rw.read(self._device, r) if reply: self._value[int(item)] = self._validator.validate_read_item(reply, item) if getattr(self._device, "persister", None) and self.name not in self._device.persister: self._device.persister[self.name] = self._value if self.persist else None return self._value[int(item)] def write(self, map, save=True): assert hasattr(self, "_value") assert hasattr(self, "_device") assert map is not None if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: long settings write %r to %s", self.name, map, self._device) if self._device.online: self.update(map, save) for item, value in map.items(): data_bytes_list = self._validator.prepare_write(self._value) if data_bytes_list is not None: for data_bytes in data_bytes_list: if data_bytes is not None: if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: settings prepare map write(%s,%s) => %r", self.name, item, value, data_bytes) reply = self._rw.write(self._device, data_bytes) if not reply: return None return map def update_key_value(self, key, value, save=True): self._value[int(key)] = value self._pre_write(save) def write_key_value(self, item, value, save=True): assert hasattr(self, "_value") assert hasattr(self, "_device") assert item is not None assert value is not None if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: long settings write item %r value %r to %s", self.name, item, value, self._device) if self._device.online: if not self._value: self.read() data_bytes = self._validator.prepare_write_item(item, value) self.update_key_value(item, value, save) if data_bytes is not None: if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: settings prepare item value write(%s,%s) => %r", self.name, item, value, data_bytes) reply = self._rw.write(self._device, data_bytes) if not reply: return None return value class BitFieldSetting(Setting): """A setting descriptor for a set of choices represented by one bit each, being a map from options to booleans. Needs to be instantiated for each specific device.""" def read(self, cached=True): assert hasattr(self, "_value") assert hasattr(self, "_device") if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: settings read %r from %s", self.name, self._value, self._device) self._pre_read(cached) if cached and self._value is not None: return self._value if self._device.online: reply_map = {} reply = self._do_read() if reply: reply_map = self._validator.validate_read(reply) self._value = reply_map if getattr(self._device, "persister", None) and self.name not in self._device.persister: # Don't update the persister if it already has a value, # otherwise the first read might overwrite the value we wanted. self._device.persister[self.name] = self._value if self.persist else None return self._value def _do_read(self): return self._rw.read(self._device) def read_key(self, key, cached=True): assert hasattr(self, "_value") assert hasattr(self, "_device") assert key is not None if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: settings read %r key %r from %s", self.name, self._value, key, self._device) self._pre_read(cached) if cached and self._value is not None: return self._value[int(key)] if self._device.online: reply = self._do_read_key(key) if reply: self._value = self._validator.validate_read(reply) if getattr(self._device, "persister", None) and self.name not in self._device.persister: self._device.persister[self.name] = self._value if self.persist else None return self._value[int(key)] def _do_read_key(self, key): return self._rw.read(self._device, key) def write(self, map, save=True): assert hasattr(self, "_value") assert hasattr(self, "_device") assert map is not None if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: bit field settings write %r to %s", self.name, map, self._device) if self._device.online: self.update(map, save) data_bytes = self._validator.prepare_write(self._value) if data_bytes is not None: if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: settings prepare map write(%s) => %r", self.name, self._value, data_bytes) # if prepare_write returns a list, write one item at a time seq = data_bytes if isinstance(data_bytes, list) else [data_bytes] for b in seq: reply = self._rw.write(self._device, b) if not reply: return None return map def update_key_value(self, key, value, save=True): self._value[int(key)] = value self._pre_write(save) def write_key_value(self, key, value, save=True): assert hasattr(self, "_value") assert hasattr(self, "_device") assert key is not None assert value is not None if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: bit field settings write key %r value %r to %s", self.name, key, value, self._device) if self._device.online: if not self._value: self.read() value = bool(value) self.update_key_value(key, value, save) data_bytes = self._validator.prepare_write(self._value) if data_bytes is not None: if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: settings prepare key value write(%s,%s) => %r", self.name, key, str(value), data_bytes) # if prepare_write returns a list, write one item at a time seq = data_bytes if isinstance(data_bytes, list) else [data_bytes] for b in seq: reply = self._rw.write(self._device, b) if not reply: return None return value class BitFieldWithOffsetAndMaskSetting(BitFieldSetting): """A setting descriptor for a set of choices represented by one bit each, each one having an offset, being a map from options to booleans. Needs to be instantiated for each specific device.""" def _do_read(self): return {r: self._rw.read(self._device, r) for r in self._validator.prepare_read()} def _do_read_key(self, key): r = self._validator.prepare_read_key(key) return {r: self._rw.read(self._device, r)} class RangeFieldSetting(Setting): """A setting descriptor for a set of choices represented by one field each, with map from option names to range(0,n). Needs to be instantiated for each specific device.""" def read(self, cached=True): assert hasattr(self, "_value") assert hasattr(self, "_device") if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: settings read %r from %s", self.name, self._value, self._device) self._pre_read(cached) if cached and self._value is not None: return self._value if self._device.online: reply_map = {} reply = self._do_read() if reply: reply_map = self._validator.validate_read(reply) self._value = reply_map if getattr(self._device, "persister", None) and self.name not in self._device.persister: # Don't update the persister if it already has a value, # otherwise the first read might overwrite the value we wanted. self._device.persister[self.name] = self._value if self.persist else None return self._value def _do_read(self): return self._rw.read(self._device) def read_key(self, key, cached=True): return self.read(cached)[int(key)] def write(self, map, save=True): assert hasattr(self, "_value") assert hasattr(self, "_device") assert map is not None if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: range field setting write %r to %s", self.name, map, self._device) if self._device.online: self.update(map, save) data_bytes = self._validator.prepare_write(self._value) if data_bytes is not None: if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: range field setting prepare map write(%s) => %r", self.name, self._value, data_bytes) reply = self._rw.write(self._device, data_bytes) if not reply: return None elif logger.isEnabledFor(logging.WARNING): logger.warning("%s: range field setting no data to write", self.name) return map def write_key_value(self, key, value, save=True): assert key is not None assert value is not None if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: range field setting write key %r value %r to %s", self.name, key, value, self._device) if self._device.online: if not self._value: self.read() map = self._value map[int(key)] = value self.write(map, save) return value # # read/write low-level operators # class RegisterRW: __slots__ = ("register",) kind = NamedInt(0x01, _("register")) def __init__(self, register: int): assert isinstance(register, int) self.register = register def read(self, device): return device.read_register(self.register) def write(self, device, data_bytes): return device.write_register(self.register, data_bytes) class FeatureRW: kind = NamedInt(0x02, _("feature")) default_read_fnid = 0x00 default_write_fnid = 0x10 def __init__( self, feature: hidpp20_constants.SupportedFeature, read_fnid=0x00, write_fnid=0x10, prefix=b"", suffix=b"", read_prefix=b"", no_reply=False, ): assert isinstance(feature, hidpp20_constants.SupportedFeature) self.feature = feature self.read_fnid = read_fnid self.write_fnid = write_fnid self.no_reply = no_reply self.prefix = prefix self.suffix = suffix self.read_prefix = read_prefix def read(self, device, data_bytes=b""): assert self.feature is not None return device.feature_request(self.feature, self.read_fnid, self.prefix, self.read_prefix, data_bytes) def write(self, device, data_bytes): assert self.feature is not None write_bytes = self.prefix + (data_bytes.to_bytes(1) if isinstance(data_bytes, int) else data_bytes) + self.suffix reply = device.feature_request(self.feature, self.write_fnid, write_bytes, no_reply=self.no_reply) return reply if not self.no_reply else True class FeatureRWMap(FeatureRW): kind = NamedInt(0x02, _("feature")) default_read_fnid = 0x00 default_write_fnid = 0x10 default_key_byte_count = 1 def __init__( self, feature: hidpp20_constants.SupportedFeature, read_fnid=default_read_fnid, write_fnid=default_write_fnid, key_byte_count=default_key_byte_count, no_reply=False, ): assert isinstance(feature, hidpp20_constants.SupportedFeature) self.feature = feature self.read_fnid = read_fnid self.write_fnid = write_fnid self.key_byte_count = key_byte_count self.no_reply = no_reply def read(self, device, key): assert self.feature is not None key_bytes = common.int2bytes(key, self.key_byte_count) return device.feature_request(self.feature, self.read_fnid, key_bytes) def write(self, device, key, data_bytes): assert self.feature is not None key_bytes = common.int2bytes(key, self.key_byte_count) reply = device.feature_request(self.feature, self.write_fnid, key_bytes, data_bytes, no_reply=self.no_reply) return reply if not self.no_reply else True class Validator: @classmethod def build(cls, setting_class, device, **kwargs): return cls(**kwargs) @classmethod def to_string(cls, value): return str(value) def compare(self, args, current): if len(args) != 1: return False return args[0] == current class BooleanValidator(Validator): __slots__ = ("true_value", "false_value", "read_skip_byte_count", "write_prefix_bytes", "mask", "needs_current_value") kind = KIND.toggle default_true = 0x01 default_false = 0x00 # mask specifies all the affected bits in the value default_mask = 0xFF def __init__( self, true_value=default_true, false_value=default_false, mask=default_mask, read_skip_byte_count=0, write_prefix_bytes=b"", ): if isinstance(true_value, int): assert isinstance(false_value, int) if mask is None: mask = self.default_mask else: assert isinstance(mask, int) assert true_value & false_value == 0 assert true_value & mask == true_value assert false_value & mask == false_value self.needs_current_value = mask != self.default_mask elif isinstance(true_value, bytes): if false_value is None or false_value == self.default_false: false_value = b"\x00" * len(true_value) else: assert isinstance(false_value, bytes) if mask is None or mask == self.default_mask: mask = b"\xff" * len(true_value) else: assert isinstance(mask, bytes) assert len(mask) == len(true_value) == len(false_value) tv = common.bytes2int(true_value) fv = common.bytes2int(false_value) mv = common.bytes2int(mask) assert tv != fv # true and false might be something other than bit values assert tv & mv == tv assert fv & mv == fv self.needs_current_value = any(m != 0xFF for m in mask) else: raise Exception(f"invalid mask '{mask!r}', type {type(mask)}") self.true_value = true_value self.false_value = false_value self.mask = mask self.read_skip_byte_count = read_skip_byte_count self.write_prefix_bytes = write_prefix_bytes def validate_read(self, reply_bytes): reply_bytes = reply_bytes[self.read_skip_byte_count :] if isinstance(self.mask, int): reply_value = ord(reply_bytes[:1]) & self.mask if logger.isEnabledFor(logging.DEBUG): logger.debug("BooleanValidator: validate read %r => %02X", reply_bytes, reply_value) if reply_value == self.true_value: return True if reply_value == self.false_value: return False logger.warning( "BooleanValidator: reply %02X mismatched %02X/%02X/%02X", reply_value, self.true_value, self.false_value, self.mask, ) return False count = len(self.mask) mask = common.bytes2int(self.mask) reply_value = common.bytes2int(reply_bytes[:count]) & mask true_value = common.bytes2int(self.true_value) if reply_value == true_value: return True false_value = common.bytes2int(self.false_value) if reply_value == false_value: return False logger.warning( "BooleanValidator: reply %r mismatched %r/%r/%r", reply_bytes, self.true_value, self.false_value, self.mask ) return False def prepare_write(self, new_value, current_value=None): if new_value is None: new_value = False else: assert isinstance(new_value, bool), f"New value {new_value} for boolean setting is not a boolean" to_write = self.true_value if new_value else self.false_value if isinstance(self.mask, int): if current_value is not None and self.needs_current_value: to_write |= ord(current_value[:1]) & (0xFF ^ self.mask) if current_value is not None and to_write == ord(current_value[:1]): return None to_write = bytes([to_write]) else: to_write = bytearray(to_write) count = len(self.mask) for i in range(0, count): b = ord(to_write[i : i + 1]) m = ord(self.mask[i : i + 1]) assert b & m == b # b &= m if current_value is not None and self.needs_current_value: b |= ord(current_value[i : i + 1]) & (0xFF ^ m) to_write[i] = b to_write = bytes(to_write) if current_value is not None and to_write == current_value[: len(to_write)]: return None if logger.isEnabledFor(logging.DEBUG): logger.debug("BooleanValidator: prepare_write(%s, %s) => %r", new_value, current_value, to_write) return self.write_prefix_bytes + to_write def acceptable(self, args, current): if len(args) != 1: return None val = bool_or_toggle(current, args[0]) return [val] if val is not None else None class BitFieldValidator(Validator): __slots__ = ("byte_count", "options") kind = KIND.multiple_toggle def __init__(self, options, byte_count=None): assert isinstance(options, list) self.options = options self.byte_count = (max(x.bit_length() for x in options) + 7) // 8 if byte_count: assert isinstance(byte_count, int) and byte_count >= self.byte_count self.byte_count = byte_count def to_string(self, value): def element_to_string(key, val): k = next((k for k in self.options if int(key) == k), None) return str(k) + ":" + str(val) if k is not None else "?" return "{" + ", ".join([element_to_string(k, value[k]) for k in value]) + "}" def validate_read(self, reply_bytes): r = common.bytes2int(reply_bytes[: self.byte_count]) value = {int(k): False for k in self.options} m = 1 for _ignore in range(8 * self.byte_count): if m in self.options: value[int(m)] = bool(r & m) m <<= 1 return value def prepare_write(self, new_value): assert isinstance(new_value, dict) w = 0 for k, v in new_value.items(): if v: w |= int(k) return common.int2bytes(w, self.byte_count) def get_options(self): return self.options def acceptable(self, args, current): if len(args) != 2: return None key = next((key for key in self.options if key == args[0]), None) if key is None: return None val = bool_or_toggle(current[int(key)], args[1]) return None if val is None else [int(key), val] def compare(self, args, current): if len(args) != 2: return False key = next((key for key in self.options if key == args[0]), None) if key is None: return False return args[1] == current[int(key)] class BitFieldWithOffsetAndMaskValidator(Validator): __slots__ = ("byte_count", "options", "_option_from_key", "_mask_from_offset", "_option_from_offset_mask") kind = KIND.multiple_toggle sep = 0x01 def __init__(self, options, om_method=None, byte_count=None): assert isinstance(options, list) # each element of options is an instance of a class # that has an id (which is used as an index in other dictionaries) # and where om_method is a method that returns a byte offset and byte mask # that says how to access and modify the bit toggle for the option self.options = options self.om_method = om_method # to retrieve the options efficiently: self._option_from_key = {} self._mask_from_offset = {} self._option_from_offset_mask = {} for opt in options: offset, mask = om_method(opt) self._option_from_key[int(opt)] = opt try: self._mask_from_offset[offset] |= mask except KeyError: self._mask_from_offset[offset] = mask try: mask_to_opt = self._option_from_offset_mask[offset] except KeyError: mask_to_opt = {} self._option_from_offset_mask[offset] = mask_to_opt mask_to_opt[mask] = opt self.byte_count = (max(om_method(x)[1].bit_length() for x in options) + 7) // 8 # is this correct?? if byte_count: assert isinstance(byte_count, int) and byte_count >= self.byte_count self.byte_count = byte_count def prepare_read(self): r = [] for offset, mask in self._mask_from_offset.items(): b = offset << (8 * (self.byte_count + 1)) b |= (self.sep << (8 * self.byte_count)) | mask r.append(common.int2bytes(b, self.byte_count + 2)) return r def prepare_read_key(self, key): option = self._option_from_key.get(key, None) if option is None: return None offset, mask = option.om_method(option) b = offset << (8 * (self.byte_count + 1)) b |= (self.sep << (8 * self.byte_count)) | mask return common.int2bytes(b, self.byte_count + 2) def validate_read(self, reply_bytes_dict): values = {int(k): False for k in self.options} for query, b in reply_bytes_dict.items(): offset = common.bytes2int(query[0:1]) b += (self.byte_count - len(b)) * b"\x00" value = common.bytes2int(b[: self.byte_count]) mask_to_opt = self._option_from_offset_mask.get(offset, {}) m = 1 for _ignore in range(8 * self.byte_count): if m in mask_to_opt: values[int(mask_to_opt[m])] = bool(value & m) m <<= 1 return values def prepare_write(self, new_value): assert isinstance(new_value, dict) w = {} for k, v in new_value.items(): option = self._option_from_key[int(k)] offset, mask = self.om_method(option) if offset not in w: w[offset] = 0 if v: w[offset] |= mask return [ common.int2bytes( (offset << (8 * (2 * self.byte_count + 1))) | (self.sep << (16 * self.byte_count)) | (self._mask_from_offset[offset] << (8 * self.byte_count)) | value, 2 * self.byte_count + 2, ) for offset, value in w.items() ] def get_options(self): return [int(opt) if isinstance(opt, int) else opt.as_int() for opt in self.options] def acceptable(self, args, current): if len(args) != 2: return None key = next((option.id for option in self.options if option.as_int() == args[0]), None) if key is None: return None val = bool_or_toggle(current[int(key)], args[1]) return None if val is None else [int(key), val] def compare(self, args, current): if len(args) != 2: return False key = next((option.id for option in self.options if option.as_int() == args[0]), None) if key is None: return False return args[1] == current[int(key)] class ChoicesValidator(Validator): """Translates between NamedInts and a byte sequence. :param choices: a list of NamedInts :param byte_count: the size of the derived byte sequence. If None, it will be calculated from the choices.""" kind = KIND.choice def __init__(self, choices=None, byte_count=None, read_skip_byte_count=0, write_prefix_bytes=b""): assert choices is not None assert isinstance(choices, NamedInts) assert len(choices) > 1 self.choices = choices self.needs_current_value = False max_bits = max(x.bit_length() for x in choices) self._byte_count = (max_bits // 8) + (1 if max_bits % 8 else 0) if byte_count: assert self._byte_count <= byte_count self._byte_count = byte_count assert self._byte_count < 8 self._read_skip_byte_count = read_skip_byte_count self._write_prefix_bytes = write_prefix_bytes if write_prefix_bytes else b"" assert self._byte_count + self._read_skip_byte_count <= 14 assert self._byte_count + len(self._write_prefix_bytes) <= 14 def to_string(self, value): return str(self.choices[value]) if isinstance(value, int) else str(value) def validate_read(self, reply_bytes): reply_value = common.bytes2int(reply_bytes[self._read_skip_byte_count : self._read_skip_byte_count + self._byte_count]) valid_value = self.choices[reply_value] assert valid_value is not None, f"{self.__class__.__name__}: failed to validate read value {reply_value:02X}" return valid_value def prepare_write(self, new_value, current_value=None): if new_value is None: value = self.choices[:][0] else: value = self.choice(new_value) if value is None: raise ValueError(f"invalid choice {new_value!r}") assert isinstance(value, NamedInt) return self._write_prefix_bytes + value.bytes(self._byte_count) def choice(self, value): if isinstance(value, int): return self.choices[value] try: int(value) if int(value) in self.choices: return self.choices[int(value)] except Exception: pass if value in self.choices: return self.choices[value] else: return None def acceptable(self, args, current): choice = self.choice(args[0]) if len(args) == 1 else None return None if choice is None else [choice] class ChoicesMapValidator(ChoicesValidator): kind = KIND.map_choice def __init__( self, choices_map, key_byte_count=0, key_postfix_bytes=b"", byte_count=0, read_skip_byte_count=0, write_prefix_bytes=b"", extra_default=None, mask=-1, activate=0, ): assert choices_map is not None assert isinstance(choices_map, dict) max_key_bits = 0 max_value_bits = 0 for key, choices in choices_map.items(): assert isinstance(key, NamedInt) assert isinstance(choices, NamedInts) max_key_bits = max(max_key_bits, key.bit_length()) for key_value in choices: assert isinstance(key_value, NamedInt) max_value_bits = max(max_value_bits, key_value.bit_length()) self._key_byte_count = (max_key_bits + 7) // 8 if key_byte_count: assert self._key_byte_count <= key_byte_count self._key_byte_count = key_byte_count self._byte_count = (max_value_bits + 7) // 8 if byte_count: assert self._byte_count <= byte_count self._byte_count = byte_count self.choices = choices_map self.needs_current_value = False self.extra_default = extra_default self._key_postfix_bytes = key_postfix_bytes self._read_skip_byte_count = read_skip_byte_count if read_skip_byte_count else 0 self._write_prefix_bytes = write_prefix_bytes if write_prefix_bytes else b"" self.activate = activate self.mask = mask assert self._byte_count + self._read_skip_byte_count + self._key_byte_count <= 14 assert self._byte_count + len(self._write_prefix_bytes) + self._key_byte_count <= 14 def to_string(self, value): def element_to_string(key, val): k, c = next(((k, c) for k, c in self.choices.items() if int(key) == k), (None, None)) return str(k) + ":" + str(c[val]) if k is not None else "?" return "{" + ", ".join([element_to_string(k, value[k]) for k in sorted(value)]) + "}" def validate_read(self, reply_bytes, key): start = self._key_byte_count + self._read_skip_byte_count end = start + self._byte_count reply_value = common.bytes2int(reply_bytes[start:end]) & self.mask # reprogrammable keys starts out as 0, which is not a choice, so don't use assert here if self.extra_default is not None and self.extra_default == reply_value: return int(self.choices[key][0]) if reply_value not in self.choices[key]: assert reply_value in self.choices[key], "%s: failed to validate read value %02X" % ( self.__class__.__name__, reply_value, ) return reply_value def prepare_key(self, key): return key.to_bytes(self._key_byte_count, "big") + self._key_postfix_bytes def prepare_write(self, key, new_value): choices = self.choices.get(key) if choices is None or (new_value not in choices and new_value != self.extra_default): logger.error("invalid choice %r for %s", new_value, key) return None new_value = new_value | self.activate return self._write_prefix_bytes + new_value.to_bytes(self._byte_count, "big") def acceptable(self, args, current): if len(args) != 2: return None key, choices = next(((key, item) for key, item in self.choices.items() if key == args[0]), (None, None)) if choices is None or args[1] not in choices: return None choice = next((item for item in choices if item == args[1]), None) return [int(key), int(choice)] if choice is not None else None def compare(self, args, current): if len(args) != 2: return False key = next((key for key in self.choices if key == int(args[0])), None) if key is None: return False return args[1] == current[int(key)] class RangeValidator(Validator): kind = KIND.range """Translates between integers and a byte sequence. :param min_value: minimum accepted value (inclusive) :param max_value: maximum accepted value (inclusive) :param byte_count: the size of the derived byte sequence. If None, it will be calculated from the range.""" min_value = 0 max_value = 255 @classmethod def build(cls, setting_class, device, **kwargs): kwargs["min_value"] = setting_class.min_value kwargs["max_value"] = setting_class.max_value return cls(**kwargs) def __init__(self, min_value=0, max_value=255, byte_count=1): assert max_value > min_value self.min_value = min_value self.max_value = max_value self.needs_current_value = True # read and check before write (needed for ADC power and probably a good idea anyway) self._byte_count = math.ceil(math.log(max_value + 1, 256)) if byte_count: assert self._byte_count <= byte_count self._byte_count = byte_count assert self._byte_count < 8 def validate_read(self, reply_bytes): reply_value = common.bytes2int(reply_bytes[: self._byte_count]) assert reply_value >= self.min_value, f"{self.__class__.__name__}: failed to validate read value {reply_value:02X}" assert reply_value <= self.max_value, f"{self.__class__.__name__}: failed to validate read value {reply_value:02X}" return reply_value def prepare_write(self, new_value, current_value=None): if new_value < self.min_value or new_value > self.max_value: raise ValueError(f"invalid choice {new_value!r}") current_value = self.validate_read(current_value) if current_value is not None else None to_write = common.int2bytes(new_value, self._byte_count) # current value is known and same as value to be written return None to signal not to write it return None if current_value is not None and current_value == new_value else to_write def acceptable(self, args, current): arg = args[0] # None if len(args) != 1 or type(arg) != int or arg < self.min_value or arg > self.max_value else args) return None if len(args) != 1 or isinstance(arg, int) or arg < self.min_value or arg > self.max_value else args def compare(self, args, current): if len(args) == 1: return args[0] == current elif len(args) == 2: return args[0] <= current <= args[1] else: return False class HeteroValidator(Validator): kind = KIND.hetero @classmethod def build(cls, setting_class, device, **kwargs): return cls(**kwargs) def __init__(self, data_class=None, options=None, readable=True): assert data_class is not None and options is not None self.data_class = data_class self.options = options self.readable = readable self.needs_current_value = False def validate_read(self, reply_bytes): if self.readable: reply_value = self.data_class.from_bytes(reply_bytes, options=self.options) return reply_value def prepare_write(self, new_value, current_value=None): to_write = new_value.to_bytes(options=self.options) return to_write def acceptable(self, args, current): # should this actually do some checking? return True class PackedRangeValidator(Validator): kind = KIND.packed_range """Several range values, all the same size, all the same min and max""" min_value = 0 max_value = 255 count = 1 rsbc = 0 write_prefix_bytes = b"" def __init__( self, keys, min_value=0, max_value=255, count=1, byte_count=1, read_skip_byte_count=0, write_prefix_bytes=b"" ): assert max_value > min_value self.needs_current_value = True self.keys = keys self.min_value = min_value self.max_value = max_value self.count = count self.bc = math.ceil(math.log(max_value + 1 - min(0, min_value), 256)) if byte_count: assert self.bc <= byte_count self.bc = byte_count assert self.bc * self.count self.rsbc = read_skip_byte_count self.write_prefix_bytes = write_prefix_bytes def validate_read(self, reply_bytes): rvs = { n: common.bytes2int(reply_bytes[self.rsbc + n * self.bc : self.rsbc + (n + 1) * self.bc], signed=True) for n in range(self.count) } for n in range(self.count): assert rvs[n] >= self.min_value, f"{self.__class__.__name__}: failed to validate read value {rvs[n]:02X}" assert rvs[n] <= self.max_value, f"{self.__class__.__name__}: failed to validate read value {rvs[n]:02X}" return rvs def prepare_write(self, new_values): if len(new_values) != self.count: raise ValueError(f"wrong number of values {new_values!r}") for new_value in new_values.values(): if new_value < self.min_value or new_value > self.max_value: raise ValueError(f"invalid value {new_value!r}") bytes = self.write_prefix_bytes + b"".join( common.int2bytes(new_values[n], self.bc, signed=True) for n in range(self.count) ) return bytes def acceptable(self, args, current): if len(args) != 2 or int(args[0]) < 0 or int(args[0]) >= self.count: return None return None if not isinstance(args[1], int) or args[1] < self.min_value or args[1] > self.max_value else args def compare(self, args, current): logger.warning("compare not implemented for packed range settings") return False class MultipleRangeValidator(Validator): kind = KIND.multiple_range def __init__(self, items, sub_items): assert isinstance(items, list) # each element must have .index and its __int__ must return its id (not its index) assert isinstance(sub_items, dict) # sub_items: items -> class with .minimum, .maximum, .length (in bytes), .id (a string) and .widget (e.g. 'Scale') self.items = items self.keys = NamedInts(**{str(item): int(item) for item in items}) self._item_from_id = {int(k): k for k in items} self.sub_items = sub_items def prepare_read_item(self, item): return common.int2bytes((self._item_from_id[int(item)].index << 1) | 0xFF, 2) def validate_read_item(self, reply_bytes, item): item = self._item_from_id[int(item)] start = 0 value = {} for sub_item in self.sub_items[item]: r = reply_bytes[start : start + sub_item.length] if len(r) < sub_item.length: r += b"\x00" * (sub_item.length - len(value)) v = common.bytes2int(r) if not (sub_item.minimum < v < sub_item.maximum): logger.warning( f"{self.__class__.__name__}: failed to validate read value for {item}.{sub_item}: " + f"{v} not in [{sub_item.minimum}..{sub_item.maximum}]" ) value[str(sub_item)] = v start += sub_item.length return value def prepare_write(self, value): seq = [] w = b"" for item in value.keys(): _item = self._item_from_id[int(item)] b = common.int2bytes(_item.index, 1) for sub_item in self.sub_items[_item]: try: v = value[int(item)][str(sub_item)] except KeyError: return None if not (sub_item.minimum <= v <= sub_item.maximum): raise ValueError( f"invalid choice for {item}.{sub_item}: {v} not in [{sub_item.minimum}..{sub_item.maximum}]" ) b += common.int2bytes(v, sub_item.length) if len(w) + len(b) > 15: seq.append(b + b"\xff") w = b"" w += b seq.append(w + b"\xff") return seq def prepare_write_item(self, item, value): _item = self._item_from_id[int(item)] w = common.int2bytes(_item.index, 1) for sub_item in self.sub_items[_item]: try: v = value[str(sub_item)] except KeyError: return None if not (sub_item.minimum <= v <= sub_item.maximum): raise ValueError(f"invalid choice for {item}.{sub_item}: {v} not in [{sub_item.minimum}..{sub_item.maximum}]") w += common.int2bytes(v, sub_item.length) return w + b"\xff" def acceptable(self, args, current): # just one item, with at least one sub-item if not isinstance(args, list) or len(args) != 2 or not isinstance(args[1], dict): return None item = next((p for p in self.items if p.id == args[0] or str(p) == args[0]), None) if not item: return None for sub_key, value in args[1].items(): sub_item = next((it for it in self.sub_items[item] if it.id == sub_key), None) if not sub_item: return None if not isinstance(value, int) or not (sub_item.minimum <= value <= sub_item.maximum): return None return [int(item), {**args[1]}] def compare(self, args, current): logger.warning("compare not implemented for multiple range settings") return False class ActionSettingRW: """Special RW class for settings that turn on and off special processing when a key or button is depressed""" def __init__(self, feature, name="", divert_setting_name="divert-keys"): self.feature = feature # not used? self.name = name self.divert_setting_name = divert_setting_name self.kind = FeatureRW.kind # pretend to be FeatureRW as required for HID++ 2.0 devices self.device = None self.key = None self.active = False self.pressed = False def activate_action(self): # action to take when setting is activated (write non-false) pass def deactivate_action(self): # action to take when setting is deactivated (write false) pass def press_action(self): # action to take when key is pressed pass def release_action(self): # action to take when key is released pass def move_action(self, dx, dy): # action to take when mouse is moved while key is down pass def key_action(self, key): # acction to take when some other diverted key is pressed pass def read(self, device): # need to return bytes, as if read from device return common.int2bytes(self.key.key, 2) if self.active and self.key else b"\x00\x00" def write(self, device, data_bytes): def handler(device, n): # Called on notification events from the device if ( n.sub_id < 0x40 and device.features.get_feature(n.sub_id) == hidpp20_constants.SupportedFeature.REPROG_CONTROLS_V4 ): if n.address == 0x00: cids = struct.unpack("!HHHH", n.data[:8]) if not self.pressed and int(self.key.key) in cids: # trigger key pressed self.pressed = True self.press_action() elif self.pressed: if int(self.key.key) not in cids: # trigger key released self.pressed = False self.release_action() else: for key in cids: if key and not key == self.key.key: # some other diverted key pressed self.key_action(key) elif n.address == 0x10: if self.pressed: dx, dy = struct.unpack("!hh", n.data[:4]) self.move_action(dx, dy) divertSetting = next(filter(lambda s: s.name == self.divert_setting_name, device.settings), None) if divertSetting is None: logger.warning("setting %s not found on %s", self.divert_setting_name, device.name) return None self.device = device key = common.bytes2int(data_bytes) if key: # Enable self.key = next((k for k in device.keys if k.key == key), None) if self.key: self.active = True if divertSetting: divertSetting.write_key_value(int(self.key.key), 1) if self.device.setting_callback: self.device.setting_callback(device, type(divertSetting), [self.key.key, 1]) device.add_notification_handler(self.name, handler) self.activate_action() else: logger.error("cannot enable %s on %s for key %s", self.name, device, key) else: # Disable if self.active: self.active = False if divertSetting: divertSetting.write_key_value(int(self.key.key), 0) if self.device.setting_callback: self.device.setting_callback(device, type(divertSetting), [self.key.key, 0]) try: device.remove_notification_handler(self.name) except Exception: if logger.isEnabledFor(logging.WARNING): logger.warning("cannot disable %s on %s", self.name, device) self.deactivate_action() return data_bytes class RawXYProcessing: """Special class for processing RawXY action messages initiated by pressing a key with rawXY diversion capability""" def __init__(self, device, name=""): self.device = device self.name = name self.keys = [] # the keys that can initiate processing self.initiating_key = None # the key that did initiate processing self.active = False self.feature_offset = device.features[hidpp20_constants.SupportedFeature.REPROG_CONTROLS_V4] assert self.feature_offset is not False def handler(self, device, n): # Called on notification events from the device if n.sub_id < 0x40 and device.features.get_feature(n.sub_id) == hidpp20_constants.SupportedFeature.REPROG_CONTROLS_V4: if n.address == 0x00: cids = struct.unpack("!HHHH", n.data[:8]) ## generalize to list of keys if not self.initiating_key: # no initiating key pressed for k in self.keys: if int(k.key) in cids: # initiating key that was pressed self.initiating_key = k if self.initiating_key: self.press_action(self.initiating_key) else: if int(self.initiating_key.key) not in cids: # initiating key released self.initiating_key = None self.release_action() else: for key in cids: if key and key != self.initiating_key.key: self.key_action(key) elif n.address == 0x10: if self.initiating_key: dx, dy = struct.unpack("!hh", n.data[:4]) self.move_action(dx, dy) def start(self, key): device_key = next((k for k in self.device.keys if k.key == key), None) if device_key: self.keys.append(device_key) if not self.active: self.active = True self.activate_action() self.device.add_notification_handler(self.name, self.handler) device_key.set_rawXY_reporting(True) def stop(self, key): # only stop if this is the active key if self.active: processing_key = next((k for k in self.keys if k.key == key), None) if processing_key: processing_key.set_rawXY_reporting(False) self.keys.remove(processing_key) if not self.keys: try: self.device.remove_notification_handler(self.name) except Exception: if logger.isEnabledFor(logging.WARNING): logger.warning("cannot disable %s on %s", self.name, self.device) self.deactivate_action() self.active = False def activate_action(self): # action to take when processing is activated pass def deactivate_action(self): # action to take when processing is deactivated pass def press_action(self, key): # action to take when an initiating key is pressed pass def release_action(self): # action to take when key is released pass def move_action(self, dx, dy): # action to take when mouse is moved while key is down pass def key_action(self, key): # acction to take when some other diverted key is pressed pass def apply_all_settings(device): if device.features and hidpp20_constants.SupportedFeature.HIRES_WHEEL in device.features: time.sleep(0.2) # delay to try to get out of race condition with Linux HID++ driver persister = getattr(device, "persister", None) sensitives = persister.get("_sensitive", {}) if persister else {} for s in device.settings: ignore = sensitives.get(s.name, False) if ignore != SENSITIVITY_IGNORE: s.apply() Setting.validator_class = BooleanValidator
63,875
Python
.py
1,339
36.763256
127
0.593267
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,459
special_keys.py
pwr-Solaar_Solaar/lib/logitech_receiver/special_keys.py
## Copyright (C) 2012-2013 Daniel Pavel ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # Reprogrammable keys information # Mostly from Logitech documentation, but with some edits for better Linux compatibility import os from enum import IntEnum import yaml from .common import NamedInts from .common import UnsortedNamedInts _XDG_CONFIG_HOME = os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser(os.path.join("~", ".config")) _keys_file_path = os.path.join(_XDG_CONFIG_HOME, "solaar", "keys.yaml") # <controls.xml awk -F\" '/<Control /{sub(/^LD_FINFO_(CTRLID_)?/, "", $2);printf("\t%s=0x%04X,\n", $2, $4)}' | sort -t= -k2 CONTROL = NamedInts( { "Volume_Up": 0x0001, "Volume_Down": 0x0002, "Mute": 0x0003, "Play__Pause": 0x0004, "Next": 0x0005, "Previous": 0x0006, "Stop": 0x0007, "Application_Switcher": 0x0008, "Burn": 0x0009, "Calculator": 0x000A, # Craft Keyboard top 4th from right "Calendar": 0x000B, "Close": 0x000C, "Eject": 0x000D, "Mail": 0x000E, "Help_As_HID": 0x000F, "Help_As_F1": 0x0010, "Launch_Word_Proc": 0x0011, "Launch_Spreadsheet": 0x0012, "Launch_Presentation": 0x0013, "Undo_As_Ctrl_Z": 0x0014, "Undo_As_HID": 0x0015, "Redo_As_Ctrl_Y": 0x0016, "Redo_As_HID": 0x0017, "Print_As_Ctrl_P": 0x0018, "Print_As_HID": 0x0019, "Save_As_Ctrl_S": 0x001A, "Save_As_HID": 0x001B, "Preset_A": 0x001C, "Preset_B": 0x001D, "Preset_C": 0x001E, "Preset_D": 0x001F, "Favorites": 0x0020, "Gadgets": 0x0021, "My_Home": 0x0022, "Gadgets_As_Win_G": 0x0023, "Maximize_As_HID": 0x0024, "Maximize_As_Win_Shift_M": 0x0025, "Minimize_As_HID": 0x0026, "Minimize_As_Win_M": 0x0027, "Media_Player": 0x0028, "Media_Center_Logi": 0x0029, "Media_Center_Msft": 0x002A, # Should not be used as it is not reprogrammable under Windows "Custom_Menu": 0x002B, "Messenger": 0x002C, "My_Documents": 0x002D, "My_Music": 0x002E, "Webcam": 0x002F, "My_Pictures": 0x0030, "My_Videos": 0x0031, "My_Computer_As_HID": 0x0032, "My_Computer_As_Win_E": 0x0033, "FN_Key": 0x0034, "Launch_Picture_Viewer": 0x0035, "One_Touch_Search": 0x0036, "Preset_1": 0x0037, "Preset_2": 0x0038, "Preset_3": 0x0039, "Preset_4": 0x003A, "Record": 0x003B, "Internet_Refresh": 0x003C, "Search": 0x003E, # SEARCH "Shuffle": 0x003F, "Sleep": 0x0040, "Internet_Stop": 0x0041, "Synchronize": 0x0042, "Zoom": 0x0043, "Zoom_In_As_HID": 0x0044, "Zoom_In_As_Ctrl_Wheel": 0x0045, "Zoom_In_As_Cltr_Plus": 0x0046, "Zoom_Out_As_HID": 0x0047, "Zoom_Out_As_Ctrl_Wheel": 0x0048, "Zoom_Out_As_Ctrl_Minus": 0x0049, "Zoom_Reset": 0x004A, "Zoom_Full_Screen": 0x004B, "Print_Screen": 0x004C, "Pause_Break": 0x004D, "Scroll_Lock": 0x004E, "Contextual_Menu": 0x004F, "Left_Button": 0x0050, # LEFT_CLICK "Right_Button": 0x0051, # RIGHT_CLICK "Middle_Button": 0x0052, # MIDDLE_BUTTON "Back_Button": 0x0053, # from M510v2 was BACK_AS_BUTTON_4 "Back": 0x0054, # BACK_AS_HID "Back_As_Alt_Win_Arrow": 0x0055, "Forward_Button": 0x0056, # from M510v2 was FORWARD_AS_BUTTON_5 "Forward_As_HID": 0x0057, "Forward_As_Alt_Win_Arrow": 0x0058, "Button_6": 0x0059, "Left_Scroll_As_Button_7": 0x005A, "Left_Tilt": 0x005B, # from M510v2 was LEFT_SCROLL_AS_AC_PAN "Right_Scroll_As_Button_8": 0x005C, "Right_Tilt": 0x005D, # from M510v2 was RIGHT_SCROLL_AS_AC_PAN "Button_9": 0x005E, "Button_10": 0x005F, "Button_11": 0x0060, "Button_12": 0x0061, "Button_13": 0x0062, "Button_14": 0x0063, "Button_15": 0x0064, "Button_16": 0x0065, "Button_17": 0x0066, "Button_18": 0x0067, "Button_19": 0x0068, "Button_20": 0x0069, "Button_21": 0x006A, "Button_22": 0x006B, "Button_23": 0x006C, "Button_24": 0x006D, "Show_Desktop": 0x006E, # Craft Keyboard Fn F5 "Lock_PC": 0x006F, # Craft Keyboard top 1st from right "Fn_F1": 0x0070, "Fn_F2": 0x0071, "Fn_F3": 0x0072, "Fn_F4": 0x0073, "Fn_F5": 0x0074, "Fn_F6": 0x0075, "Fn_F7": 0x0076, "Fn_F8": 0x0077, "Fn_F9": 0x0078, "Fn_F10": 0x0079, "Fn_F11": 0x007A, "Fn_F12": 0x007B, "Fn_F13": 0x007C, "Fn_F14": 0x007D, "Fn_F15": 0x007E, "Fn_F16": 0x007F, "Fn_F17": 0x0080, "Fn_F18": 0x0081, "Fn_F19": 0x0082, "IOS_Home": 0x0083, "Android_Home": 0x0084, "Android_Menu": 0x0085, "Android_Search": 0x0086, "Android_Back": 0x0087, "Home_Combo": 0x0088, "Lock_Combo": 0x0089, "IOS_Virtual_Keyboard": 0x008A, "IOS_Language_Switch": 0x008B, "Mac_Expose": 0x008C, "Mac_Dashboard": 0x008D, "Win7_Snap_Left": 0x008E, "Win7_Snap_Right": 0x008F, "Minimize_Window": 0x0090, # WIN7_MINIMIZE_AS_WIN_ARROW "Maximize_Window": 0x0091, # WIN7_MAXIMIZE_AS_WIN_ARROW "Win7_Stretch_Up": 0x0092, "Win7_Monitor_Switch_As_Win_Shift_LeftArrow": 0x0093, "Win7_Monitor_Switch_As_Win_Shift_RightArrow": 0x0094, "Switch_Screen": 0x0095, # WIN7_SHOW_PRESENTATION_MODE "Win7_Show_Mobility_Center": 0x0096, "Analog_HScroll": 0x0097, "Metro_Appswitch": 0x009F, "Metro_Appbar": 0x00A0, "Metro_Charms": 0x00A1, "Calc_Vkeyboard": 0x00A2, "Metro_Search": 0x00A3, "Combo_Sleep": 0x00A4, "Metro_Share": 0x00A5, "Metro_Settings": 0x00A6, "Metro_Devices": 0x00A7, "Metro_Start_Screen": 0x00A9, "Zoomin": 0x00AA, "Zoomout": 0x00AB, "Back_Hscroll": 0x00AC, "Show_Desktop_HPP": 0x00AE, "Fn_Left_Click": 0x00B7, # from K400 Plus # https://docs.google.com/document/u/0/d/1YvXICgSe8BcBAuMr4Xu_TutvAxaa-RnGfyPFWBWzhkc/export?format=docx # Extract to csv. Eliminate extra linefeeds and spaces. # awk -F, '/0x/{gsub(" \\+ ","_",$2); gsub("/","__",$2); gsub(" -","_Down",$2); # gsub(" \\+","_Up",$2); gsub("[()\"-]","",$2); gsub(" ","_",$2); printf("\t%s=0x%04X,\n", $2, $1)}' < controls.cvs "Second_Left_Click": 0x00B8, # Second_LClick / on K400 Plus "Fn_Second_Left_Click": 0x00B9, # Fn_Second_LClick "Multiplatform_App_Switch": 0x00BA, "Multiplatform_Home": 0x00BB, "Multiplatform_Menu": 0x00BC, "Multiplatform_Back": 0x00BD, "Multiplatform_Insert": 0x00BE, "Screen_Capture__Print_Screen": 0x00BF, # Craft Keyboard top 3rd from right "Fn_Down": 0x00C0, "Fn_Up": 0x00C1, "Multiplatform_Lock": 0x00C2, "Mouse_Gesture_Button": 0x00C3, # Thumb_Button on MX Master - Logitech name App_Switch_Gesture "Smart_Shift": 0x00C4, # Top_Button on MX Master "Microphone": 0x00C5, "Wifi": 0x00C6, "Brightness_Down": 0x00C7, # Craft Keyboard Fn F1 "Brightness_Up": 0x00C8, # Craft Keyboard Fn F2 "Display_Out__Project_Screen_": 0x00C9, "View_Open_Apps": 0x00CA, "View_All_Apps": 0x00CB, "Switch_App": 0x00CC, "Fn_Inversion_Change": 0x00CD, "MultiPlatform_Back": 0x00CE, "MultiPlatform_Forward": 0x00CF, "MultiPlatform_Gesture_Button": 0x00D0, "Host_Switch_Channel_1": 0x00D1, # Craft Keyboard "Host_Switch_Channel_2": 0x00D2, # Craft Keyboard "Host_Switch_Channel_3": 0x00D3, # Craft Keyboard "MultiPlatform_Search": 0x00D4, "MultiPlatform_Home__Mission_Control": 0x00D5, "MultiPlatform_Menu__Show__Hide_Virtual_Keyboard__Launchpad": 0x00D6, "Virtual_Gesture_Button": 0x00D7, "Cursor_Button_Long_Press": 0x00D8, "Next_Button_Shortpress": 0x00D9, # Next_Button "Next_Button_Long_Press": 0x00DA, "Back_Button_Short_Press": 0x00DB, # Back "Back_Button_Long_Press": 0x00DC, "Multi_Platform_Language_Switch": 0x00DD, "F_Lock": 0x00DE, "Switch_Highlight": 0x00DF, "Mission_Control__Task_View": 0x00E0, # Craft Keyboard Fn F3 Switch_Workspace "Dashboard_Launchpad__Action_Center": 0x00E1, # Craft Keyboard Fn F4 Application_Launcher "Backlight_Down": 0x00E2, # Craft Keyboard Fn F6 "Backlight_Up": 0x00E3, # Craft Keyboard Fn F7 "Previous_Fn": 0x00E4, # Craft Keyboard Fn F8 Previous_Track "Play__Pause_Fn": 0x00E5, # Craft Keyboard Fn F9 Play__Pause "Next_Fn": 0x00E6, # Craft Keyboard Fn F10 Next_Track "Mute_Fn": 0x00E7, # Craft Keyboard Fn F11 Mute "Volume_Down_Fn": 0x00E8, # Craft Keyboard Fn F12 Volume_Down "Volume_Up_Fn": 0x00E9, # Craft Keyboard next to F12 Volume_Down "App_Contextual_Menu__Right_Click": 0x00EA, # Craft Keyboard top 2nd from right "Right_Arrow": 0x00EB, "Left_Arrow": 0x00EC, "DPI_Change": 0x00ED, "New_Tab": 0x00EE, "F2": 0x00EF, "F3": 0x00F0, "F4": 0x00F1, "F5": 0x00F2, "F6": 0x00F3, "F7": 0x00F4, "F8": 0x00F5, "F1": 0x00F6, "Next_Color_Effect": 0x00F7, "Increase_Color_Effect_Speed": 0x00F8, "Decrease_Color_Effect_Speed": 0x00F9, "Load_Lighting_Custom_Profile": 0x00FA, "Laser_Button_Short_Press": 0x00FB, "Laser_Button_Long_Press": 0x00FC, "DPI_Switch": 0x00FD, "Multiplatform_Home__Show_Desktop": 0x00FE, "Multiplatform_App_Switch__Show_Dashboard": 0x00FF, "Multiplatform_App_Switch_2": 0x0100, # Multiplatform_App_Switch "Fn_Inversion__Hot_Key": 0x0101, "LeftAndRightClick": 0x0102, "Voice_Dictation": 0x0103, # MX Keys for Business Fn F5 ; MX Mini Fn F6 Dictation "Emoji_Smiley_Heart_Eyes": 0x0104, "Emoji_Crying_Face": 0x0105, "Emoji_Smiley": 0x0106, "Emoji_Smilie_With_Tears": 0x0107, "Open_Emoji_Panel": 0x0108, # MX Keys for Business Fn F6 ; MX Mini Fn F7 Emoji "Multiplatform_App_Switch__Launchpad": 0x0109, "Snipping_Tool": 0x010A, # MX Keys for Business top 3rd from right; MX Mini Fn F8 Screenshot "Grave_Accent": 0x010B, "Tab_Key": 0x010C, "Caps_Lock": 0x010D, "Left_Shift": 0x010E, "Left_Control": 0x010F, "Left_Option__Start": 0x0110, "Left_Command__Alt": 0x0111, "Right_Command__Alt": 0x0112, "Right_Option__Start": 0x0113, "Right_Control": 0x0114, "Right_Shift": 0x0115, "Insert": 0x0116, "Delete": 0x0117, # MX Mini Lock (on delete key in function row) "Home": 0x118, "End": 0x119, "Page_Up": 0x11A, "Page_Down": 0x11B, "Mute_Microphone": 0x11C, # MX Keys for Business Fn F7 ; MX Mini Fn F9 Microphone Mute "Do_Not_Disturb": 0x11D, "Backslash": 0x11E, "Refresh": 0x11F, "Close_Tab": 0x120, "Lang_Switch": 0x121, "Standard_Key_A": 0x122, "Standard_Key_B": 0x123, "Standard_Key_C": 0x124, # There are lots more of these "Right_Option__Start__2": 0x013C, # On MX Mechanical Mini "Play_Pause": 0x0141, # On MX Mechanical Mini } ) for i in range(1, 33): # add in G keys - these are not really Logitech Controls CONTROL[0x1000 + i] = "G" + str(i) for i in range(1, 9): # add in M keys - these are not really Logitech Controls CONTROL[0x1100 + i] = "M" + str(i) CONTROL[0x1200] = "MR" # add in MR key - this is not really a Logitech Control CONTROL._fallback = lambda x: f"unknown:{x:04X}" # <tasks.xml awk -F\" '/<Task /{gsub(/ /, "_", $6); printf("\t%s=0x%04X,\n", $6, $4)}' TASK = NamedInts( Volume_Up=0x0001, Volume_Down=0x0002, Mute=0x0003, # Multimedia tasks: Play__Pause=0x0004, Next=0x0005, Previous=0x0006, Stop=0x0007, Application_Switcher=0x0008, BurnMediaPlayer=0x0009, Calculator=0x000A, Calendar=0x000B, Close_Application=0x000C, Eject=0x000D, Email=0x000E, Help=0x000F, OffDocument=0x0010, OffSpreadsheet=0x0011, OffPowerpnt=0x0012, Undo=0x0013, Redo=0x0014, Print=0x0015, Save=0x0016, SmartKeySet=0x0017, Favorites=0x0018, GadgetsSet=0x0019, HomePage=0x001A, WindowsRestore=0x001B, WindowsMinimize=0x001C, Music=0x001D, # also known as MediaPlayer # Both 0x001E and 0x001F are known as MediaCenterSet Media_Center_Logitech=0x001E, Media_Center_Microsoft=0x001F, UserMenu=0x0020, Messenger=0x0021, PersonalFolders=0x0022, MyMusic=0x0023, Webcam=0x0024, PicturesFolder=0x0025, MyVideos=0x0026, My_Computer=0x0027, PictureAppSet=0x0028, Search=0x0029, # also known as AdvSmartSearch RecordMediaPlayer=0x002A, BrowserRefresh=0x002B, RotateRight=0x002C, Search_Files=0x002D, # SearchForFiles MM_SHUFFLE=0x002E, Sleep=0x002F, # also known as StandBySet BrowserStop=0x0030, OneTouchSync=0x0031, ZoomSet=0x0032, ZoomBtnInSet2=0x0033, ZoomBtnInSet=0x0034, ZoomBtnOutSet2=0x0035, ZoomBtnOutSet=0x0036, ZoomBtnResetSet=0x0037, Left_Click=0x0038, # LeftClick Right_Click=0x0039, # RightClick Mouse_Middle_Button=0x003A, # from M510v2 was MiddleMouseButton Back=0x003B, Mouse_Back_Button=0x003C, # from M510v2 was BackEx BrowserForward=0x003D, Mouse_Forward_Button=0x003E, # from M510v2 was BrowserForwardEx Mouse_Scroll_Left_Button_=0x003F, # from M510v2 was HorzScrollLeftSet Mouse_Scroll_Right_Button=0x0040, # from M510v2 was HorzScrollRightSet QuickSwitch=0x0041, BatteryStatus=0x0042, Show_Desktop=0x0043, # ShowDesktop WindowsLock=0x0044, FileLauncher=0x0045, FolderLauncher=0x0046, GotoWebAddress=0x0047, GenericMouseButton=0x0048, KeystrokeAssignment=0x0049, LaunchProgram=0x004A, MinMaxWindow=0x004B, VOLUMEMUTE_NoOSD=0x004C, New=0x004D, Copy=0x004E, CruiseDown=0x004F, CruiseUp=0x0050, Cut=0x0051, Do_Nothing=0x0052, PageDown=0x0053, PageUp=0x0054, Paste=0x0055, SearchPicture=0x0056, Reply=0x0057, PhotoGallerySet=0x0058, MM_REWIND=0x0059, MM_FASTFORWARD=0x005A, Send=0x005B, ControlPanel=0x005C, UniversalScroll=0x005D, AutoScroll=0x005E, GenericButton=0x005F, MM_NEXT=0x0060, MM_PREVIOUS=0x0061, Do_Nothing_One=0x0062, # also known as Do_Nothing SnapLeft=0x0063, SnapRight=0x0064, WinMinRestore=0x0065, WinMaxRestore=0x0066, WinStretch=0x0067, SwitchMonitorLeft=0x0068, SwitchMonitorRight=0x0069, ShowPresentation=0x006A, ShowMobilityCenter=0x006B, HorzScrollNoRepeatSet=0x006C, TouchBackForwardHorzScroll=0x0077, MetroAppSwitch=0x0078, MetroAppBar=0x0079, MetroCharms=0x007A, Calculator_VKEY=0x007B, # also known as Calculator MetroSearch=0x007C, MetroStartScreen=0x0080, MetroShare=0x007D, MetroSettings=0x007E, MetroDevices=0x007F, MetroBackLeftHorz=0x0082, MetroForwRightHorz=0x0083, Win8_Back=0x0084, # also known as MetroCharms Win8_Forward=0x0085, # also known as AppSwitchBar Win8Charm_Appswitch_GifAnimation=0x0086, Win8BackHorzLeft=0x008B, # also known as Back Win8ForwardHorzRight=0x008C, # also known as BrowserForward MetroSearch2=0x0087, MetroShare2=0x0088, MetroSettings2=0x008A, MetroDevices2=0x0089, Win8MetroWin7Forward=0x008D, # also known as MetroStartScreen Win8ShowDesktopWin7Back=0x008E, # also known as ShowDesktop MetroApplicationSwitch=0x0090, # also known as MetroStartScreen ShowUI=0x0092, # https://docs.google.com/document/d/1Dpx_nWRQAZox_zpZ8SNc9nOkSDE9svjkghOCbzopabc/edit # Extract to csv. Eliminate extra linefeeds and spaces. Turn / into __ and space into _ # awk -F, '/0x/{gsub(" \\+ ","_",$2); gsub("_-","_Down",$2); gsub("_\\+","_Up",$2); # gsub("[()\"-]","",$2); gsub(" ","_",$2); printf("\t%s=0x%04X,\n", $2, $1)}' < tasks.csv > tasks.py Switch_Presentation__Switch_Screen=0x0093, # on K400 Plus Minimize_Window=0x0094, Maximize_Window=0x0095, # on K400 Plus MultiPlatform_App_Switch=0x0096, MultiPlatform_Home=0x0097, MultiPlatform_Menu=0x0098, MultiPlatform_Back=0x0099, Switch_Language=0x009A, # Mac_switch_language Screen_Capture=0x009B, # Mac_screen_Capture, on Craft Keyboard Gesture_Button=0x009C, Smart_Shift=0x009D, AppExpose=0x009E, Smart_Zoom=0x009F, Lookup=0x00A0, Microphone_on__off=0x00A1, Wifi_on__off=0x00A2, Brightness_Down=0x00A3, Brightness_Up=0x00A4, Display_Out=0x00A5, View_Open_Apps=0x00A6, View_All_Open_Apps=0x00A7, AppSwitch=0x00A8, Gesture_Button_Navigation=0x00A9, # Mouse_Thumb_Button on MX Master Fn_inversion=0x00AA, Multiplatform_Back=0x00AB, Multiplatform_Forward=0x00AC, Multiplatform_Gesture_Button=0x00AD, HostSwitch_Channel_1=0x00AE, HostSwitch_Channel_2=0x00AF, HostSwitch_Channel_3=0x00B0, Multiplatform_Search=0x00B1, Multiplatform_Home__Mission_Control=0x00B2, Multiplatform_Menu__Launchpad=0x00B3, Virtual_Gesture_Button=0x00B4, Cursor=0x00B5, Keyboard_Right_Arrow=0x00B6, SW_Custom_Highlight=0x00B7, Keyboard_Left_Arrow=0x00B8, TBD=0x00B9, Multiplatform_Language_Switch=0x00BA, SW_Custom_Highlight_2=0x00BB, Fast_Forward=0x00BC, Fast_Backward=0x00BD, Switch_Highlighting=0x00BE, Mission_Control__Task_View=0x00BF, # Switch_Workspace on Craft Keyboard Dashboard_Launchpad__Action_Center=0x00C0, # Application_Launcher on Craft Keyboard Backlight_Down=0x00C1, # Backlight_Down_FW_internal_function Backlight_Up=0x00C2, # Backlight_Up_FW_internal_function Right_Click__App_Contextual_Menu=0x00C3, # Context_Menu on Craft Keyboard DPI_Change=0x00C4, New_Tab=0x00C5, F2=0x00C6, F3=0x00C7, F4=0x00C8, F5=0x00C9, F6=0x00CA, F7=0x00CB, F8=0x00CC, F1=0x00CD, Laser_Button=0x00CE, Laser_Button_Long_Press=0x00CF, Start_Presentation=0x00D0, Blank_Screen=0x00D1, DPI_Switch=0x00D2, # AdjustDPI on MX Vertical Home__Show_Desktop=0x00D3, App_Switch__Dashboard=0x00D4, App_Switch=0x00D5, Fn_Inversion=0x00D6, LeftAndRightClick=0x00D7, Voice_Dictation=0x00D8, Emoji_Smiling_Face_With_Heart_Shaped_Eyes=0x00D9, Emoji_Loudly_Crying_Face=0x00DA, Emoji_Smiley=0x00DB, Emoji_Smiley_With_Tears=0x00DC, Open_Emoji_Panel=0x00DD, Multiplatform_App_Switch__Launchpad=0x00DE, Snipping_Tool=0x00DF, Grave_Accent=0x00E0, Standard_Tab_Key=0x00E1, Caps_Lock=0x00E2, Left_Shift=0x00E3, Left_Control=0x00E4, Left_Option__Start=0x00E5, Left_Command__Alt=0x00E6, Right_Command__Alt=0x00E7, Right_Option__Start=0x00E8, Right_Control=0x00E9, Right_Shift=0x0EA, Insert=0x00EB, Delete=0x00EC, Home=0x00ED, End=0x00EE, Page_Up=0x00EF, Page_Down=0x00F0, Mute_Microphone=0x00F1, Do_Not_Disturb=0x00F2, Backslash=0x00F3, Refresh=0x00F4, Close_Tab=0x00F5, Lang_Switch=0x00F6, Standard_Alphabetical_Key=0x00F7, Right_Option__Start__2=0x00F8, Left_Option=0x00F9, Right_Option=0x00FA, Left_Cmd=0x00FB, Right_Cmd=0x00FC, ) TASK._fallback = lambda x: f"unknown:{x:04X}" # Capabilities and desired software handling for a control # Ref: https://drive.google.com/file/d/10imcbmoxTJ1N510poGdsviEhoFfB_Ua4/view # We treat bytes 4 and 8 of `getCidInfo` as a single bitfield KEY_FLAG = NamedInts( analytics_key_events=0x400, force_raw_XY=0x200, raw_XY=0x100, virtual=0x80, persistently_divertable=0x40, divertable=0x20, reprogrammable=0x10, FN_sensitive=0x08, nonstandard=0x04, is_FN=0x02, mse=0x01, ) # Flags describing the reporting method of a control # We treat bytes 2 and 5 of `get/setCidReporting` as a single bitfield MAPPING_FLAG = NamedInts( analytics_key_events_reporting=0x100, force_raw_XY_diverted=0x40, raw_XY_diverted=0x10, persistently_diverted=0x04, diverted=0x01, ) class CIDGroupBit(IntEnum): g1 = 0x01 g2 = 0x02 g3 = 0x04 g4 = 0x08 g5 = 0x10 g6 = 0x20 g7 = 0x40 g8 = 0x80 class CidGroup(IntEnum): g1 = 1 g2 = 2 g3 = 3 g4 = 4 g5 = 5 g6 = 6 g7 = 7 g8 = 8 DISABLE = NamedInts( Caps_Lock=0x01, Num_Lock=0x02, Scroll_Lock=0x04, Insert=0x08, Win=0x10, # aka Super ) DISABLE._fallback = lambda x: f"unknown:{x:02X}" # HID USB Keycodes from https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf # Modified by information from Linux HID driver linux/drivers/hid/hid-input.c USB_HID_KEYCODES = NamedInts( A=0x04, B=0x05, C=0x06, D=0x07, E=0x08, F=0x09, G=0x0A, H=0x0B, I=0x0C, J=0x0D, K=0x0E, L=0x0F, M=0x10, N=0x11, O=0x12, P=0x13, Q=0x14, R=0x15, S=0x16, T=0x17, U=0x18, V=0x19, W=0x1A, X=0x1B, Y=0x1C, Z=0x1D, ENTER=0x28, ESC=0x29, BACKSPACE=0x2A, TAB=0x2B, SPACE=0x2C, MINUS=0x2D, EQUAL=0x2E, LEFTBRACE=0x2F, RIGHTBRACE=0x30, BACKSLASH=0x31, HASHTILDE=0x32, SEMICOLON=0x33, APOSTROPHE=0x34, GRAVE=0x35, COMMA=0x36, DOT=0x37, SLASH=0x38, CAPSLOCK=0x39, F1=0x3A, F2=0x3B, F3=0x3C, F4=0x3D, F5=0x3E, F6=0x3F, F7=0x40, F8=0x41, F9=0x42, F10=0x43, F11=0x44, F12=0x45, SYSRQ=0x46, SCROLLLOCK=0x47, PAUSE=0x48, INSERT=0x49, HOME=0x4A, PAGEUP=0x4B, DELETE=0x4C, END=0x4D, PAGEDOWN=0x4E, RIGHT=0x4F, LEFT=0x50, DOWN=0x51, UP=0x52, NUMLOCK=0x53, KPSLASH=0x54, KPASTERISK=0x55, KPMINUS=0x56, KPPLUS=0x57, KPENTER=0x58, KP1=0x59, KP2=0x5A, KP3=0x5B, KP4=0x5C, KP5=0x5D, KP6=0x5E, KP7=0x5F, KP8=0x60, KP9=0x61, KP0=0x62, KPDOT=0x63, COMPOSE=0x65, POWER=0x66, KPEQUAL=0x67, F13=0x68, F14=0x69, F15=0x6A, F16=0x6B, F17=0x6C, F18=0x6D, F19=0x6E, F20=0x6F, F21=0x70, F22=0x71, F23=0x72, F24=0x73, OPEN=0x74, HELP=0x75, PROPS=0x76, FRONT=0x77, STOP=0x78, AGAIN=0x79, UNDO=0x7A, CUT=0x7B, COPY=0x7C, PASTE=0x7D, FIND=0x7E, MUTE=0x7F, VOLUMEUP=0x80, VOLUMEDOWN=0x81, KPCOMMA=0x85, RO=0x87, KATAKANAHIRAGANA=0x88, YEN=0x89, HENKAN=0x8A, MUHENKAN=0x8B, KPJPCOMMA=0x8C, HANGEUL=0x90, HANJA=0x91, KATAKANA=0x92, HIRAGANA=0x93, ZENKAKUHANKAKU=0x94, KPLEFTPAREN=0xB6, KPRIGHTPAREN=0xB7, LEFTCTRL=0xE0, LEFTSHIFT=0xE1, LEFTALT=0xE2, LEFTWINDOWS=0xE3, RIGHTCTRL=0xE4, RIGHTSHIFT=0xE5, RIGHTALT=0xE6, RIGHTMETA=0xE7, MEDIA_PLAYPAUSE=0xE8, MEDIA_STOPCD=0xE9, MEDIA_PREVIOUSSONG=0xEA, MEDIA_NEXTSONG=0xEB, MEDIA_EJECTCD=0xEC, MEDIA_VOLUMEUP=0xED, MEDIA_VOLUMEDOWN=0xEE, MEDIA_MUTE=0xEF, MEDIA_WWW=0xF0, MEDIA_BACK=0xF1, MEDIA_FORWARD=0xF2, MEDIA_STOP=0xF3, MEDIA_FIND=0xF4, MEDIA_SCROLLUP=0xF5, MEDIA_SCROLLDOWN=0xF6, MEDIA_EDIT=0xF7, MEDIA_SLEEP=0xF8, MEDIA_COFFEE=0xF9, MEDIA_REFRESH=0xFA, MEDIA_CALC=0xFB, ) USB_HID_KEYCODES[0] = "No Output" USB_HID_KEYCODES[0x1E] = "1" USB_HID_KEYCODES[0x1F] = "2" USB_HID_KEYCODES[0x20] = "3" USB_HID_KEYCODES[0x21] = "4" USB_HID_KEYCODES[0x22] = "5" USB_HID_KEYCODES[0x23] = "6" USB_HID_KEYCODES[0x24] = "7" USB_HID_KEYCODES[0x25] = "8" USB_HID_KEYCODES[0x26] = "9" USB_HID_KEYCODES[0x27] = "0" USB_HID_KEYCODES[0x64] = "102ND" HID_CONSUMERCODES = NamedInts( { # Unassigned=0x00, # Consumer_Control=0x01, # Numeric_Key_Pad=0x02, # Programmable_Buttons=0x03, # Microphone=0x04, # Headphone=0x05, # Graphic_Equalizer=0x06, # AM__PM=0x22, "Power": 0x30, "Reset": 0x31, "Sleep": 0x32, "Sleep_After": 0x33, "Sleep_Mode": 0x34, "Illumination": 0x35, "Function_Buttons": 0x36, "Menu": 0x40, "Menu__Pick": 0x41, "Menu_Up": 0x42, "Menu_Down": 0x43, "Menu_Left": 0x44, "Menu_Right": 0x45, "Menu_Escape": 0x46, "Menu_Value_Increase": 0x47, "Menu_Value_Decrease": 0x48, "Data_On_Screen": 0x60, "Closed_Caption": 0x61, # Closed_Caption_Select=0x62, "VCR__TV": 0x63, # Broadcast_Mode=0x64, "Snapshot": 0x65, # Still=0x66, "Red": 0x69, "Green": 0x6A, "Blue": 0x6B, "Yellow": 0x6C, "Aspect_Ratio": 0x6D, "Brightness_Up": 0x6F, "Brightness_Down": 0x70, "Brightness_Toggle": 0x72, "Brightness_Min": 0x73, "Brightness_Max": 0x74, "Brightness_Auto": 0x75, "Keyboard_Illumination_Up": 0x79, "Keyboard_Illumination_Down": 0x7A, "Keyboard_Illumination_Toggle": 0x7C, # Selection=0x80, # Assign_Selection=0x81, "Mode_Step": 0x82, "Recall_Last": 0x83, "Enter_Channel": 0x84, # Order_Movie=0x85, # Channel=0x86, # Media_Selection=0x87, "Media_Select_Computer": 0x88, "Media_Select_TV": 0x89, "Media_Select_WWW": 0x8A, "Media_Select_DVD": 0x8B, "Media_Select_Telephone": 0x8C, "Media_Select_Program_Guide": 0x8D, "Media_Select_Video_Phone": 0x8E, "Media_Select_Games": 0x8F, "Media_Select_Messages": 0x90, "Media_Select_CD": 0x91, "Media_Select_VCR": 0x92, "Media_Select_Tuner": 0x93, "Quit": 0x94, "Help": 0x95, "Media_Select_Tape": 0x96, "Media_Select_Cable": 0x97, "Media_Select_Satellite": 0x98, "Media_Select_Security": 0x99, "Media_Select_Home": 0x9A, # Media_Select_Call=0x9B, "Channel_Increment": 0x9C, "Channel_Decrement": 0x9D, # Media_Select_SAP=0x9E, "VCR_Plus": 0xA0, # Once=0xA1, # Daily=0xA2, # Weekly=0xA3, # Monthly=0xA4, "Play": 0xB0, "Pause": 0xB1, "Record": 0xB2, "Fast_Forward": 0xB3, "Rewind": 0xB4, "Scan_Next_Track": 0xB5, "Scan_Previous_Track": 0xB6, "Stop": 0xB7, "Eject": 0xB8, "Random_Play": 0xB9, "Select_DisC": 0xBA, "Enter_Disc": 0xBB, "Repeat": 0xBC, "Tracking": 0xBD, "Track_Normal": 0xBE, "Slow_Tracking": 0xBF, # Frame_Forward=0xC0, # Frame_Back=0xC1, # Mark=0xC2, # Clear_Mark=0xC3, # Repeat_From_Mark=0xC4, # Return_To_Mark=0xC5, # Search_Mark_Forward=0xC6, # Search_Mark_Backwards=0xC7, # Counter_Reset=0xC8, # Show_Counter=0xC9, # Tracking_Increment=0xCA, # Tracking_Decrement=0xCB, # Stop__Eject=0xCC, "Play__Pause": 0xCD, # Play__Skip=0xCE, "Volume": 0xE0, # Balance=0xE1, "Mute": 0xE2, # Bass=0xE3, # Treble=0xE4, "Bass_Boost": 0xE5, # Surround_Mode=0xE6, # Loudness=0xE7, # MPX=0xE8, "Volume_Up": 0xE9, "Volume_Down": 0xEA, # Speed_Select=0xF0, # Playback_Speed=0xF1, # Standard_Play=0xF2, # Long_Play=0xF3, # Extended_Play=0xF4, "Slow": 0xF5, "Fan_Enable": 0x100, "Fan_Speed": 0x101, "Light": 0x102, "Light_Illumination_Level": 0x103, "Climate_Control_Enable": 0x104, "Room_Temperature": 0x105, "Security_Enable": 0x106, "Fire_Alarm": 0x107, "Police_Alarm": 0x108, "Proximity": 0x109, "Motion": 0x10A, "Duress_Alarm": 0x10B, "Holdup_Alarm": 0x10C, "Medical_Alarm": 0x10D, "Balance_Right": 0x150, "Balance_Left": 0x151, "Bass_Increment": 0x152, "Bass_Decrement": 0x153, "Treble_Increment": 0x154, "Treble_Decrement": 0x155, "Speaker_System": 0x160, "Channel_Left": 0x161, "Channel_Right": 0x162, "Channel_Center": 0x163, "Channel_Front": 0x164, "Channel_Center_Front": 0x165, "Channel_Side": 0x166, "Channel_Surround": 0x167, "Channel_Low_Frequency_Enhancement": 0x168, "Channel_Top": 0x169, "Channel_Unknown": 0x16A, "Subchannel": 0x170, "Subchannel_Increment": 0x171, "Subchannel_Decrement": 0x172, "Alternate_Audio_Increment": 0x173, "Alternate_Audio_Decrement": 0x174, "Application_Launch_Buttons": 0x180, "AL_Launch_Button_Configuration_Tool": 0x181, "AL_Programmable_Button_Configuration": 0x182, "AL_Consumer_Control_Configuration": 0x183, "AL_Word_Processor": 0x184, "AL_Text_Editor": 0x185, "AL_Spreadsheet": 0x186, "AL_Graphics_Editor": 0x187, "AL_Presentation_App": 0x188, "AL_Database_App": 0x189, "AL_Email_Reader": 0x18A, "AL_Newsreader": 0x18B, "AL_Voicemail": 0x18C, "AL_Contacts__Address_Book": 0x18D, "AL_Calendar__Schedule": 0x18E, "AL_Task__Project_Manager": 0x18F, "AL_Log__Journal__Timecard": 0x190, "AL_Checkbook__Finance": 0x191, "AL_Calculator": 0x192, "AL_A__V_Capture__Playback": 0x193, "AL_Local_Machine_Browser": 0x194, "AL_LAN__WAN_Browser": 0x195, "AL_Internet_Browser": 0x196, "AL_Remote_Networking__ISP_Connect": 0x197, "AL_Network_Conference": 0x198, "AL_Network_Chat": 0x199, "AL_Telephony__Dialer": 0x19A, "AL_Logon": 0x19B, "AL_Logoff": 0x19C, "AL_Logon__Logoff": 0x19D, "AL_Terminal_Lock__Screensaver": 0x19E, "AL_Control_Panel": 0x19F, "AL_Command_Line_Processor__Run": 0x1A0, "AL_Process__Task_Manager": 0x1A1, "AL_Select_Tast__Application": 0x1A2, "AL_Next_Task__Application": 0x1A3, "AL_Previous_Task__Application": 0x1A4, "AL_Preemptive_Halt_Task__Application": 0x1A5, "AL_Integrated_Help_Center": 0x1A6, "AL_Documents": 0x1A7, "AL_Thesaurus": 0x1A8, "AL_Dictionary": 0x1A9, "AL_Desktop": 0x1AA, "AL_Spell_Check": 0x1AB, "AL_Grammar_Check": 0x1AC, "AL_Wireless_Status": 0x1AD, "AL_Keyboard_Layout": 0x1AE, "AL_Virus_Protection": 0x1AF, "AL_Encryption": 0x1B0, "AL_Screen_Saver": 0x1B1, "AL_Alarms": 0x1B2, "AL_Clock": 0x1B3, "AL_File_Browser": 0x1B4, "AL_Power_Status": 0x1B5, "AL_Image_Browser": 0x1B6, "AL_Audio_Browser": 0x1B7, "AL_Movie_Browser": 0x1B8, "AL_Digital_Rights_Manager": 0x1B9, "AL_Digital_Wallet": 0x1BA, "AL_Instant_Messaging": 0x1BC, "AL_OEM_Features___Tips__Tutorial_Browser": 0x1BD, "AL_OEM_Help": 0x1BE, "AL_Online_Community": 0x1BF, "AL_Entertainment_Content_Browser": 0x1C0, "AL_Online_Shopping_Browser": 0x1C1, "AL_SmartCard_Information__Help": 0x1C2, "AL_Market_Monitor__Finance_Browser": 0x1C3, "AL_Customized_Corporate_News_Browser": 0x1C4, "AL_Online_Activity_Browser": 0x1C5, "AL_Research__Search_Browser": 0x1C6, "AL_Audio_Player": 0x1C7, "Generic_GUI_Application_Controls": 0x200, "AC_New": 0x201, "AC_Open": 0x202, "AC_Close": 0x203, "AC_Exit": 0x204, "AC_Maximize": 0x205, "AC_Minimize": 0x206, "AC_Save": 0x207, "AC_Print": 0x208, "AC_Properties": 0x209, "AC_Undo": 0x21A, "AC_Copy": 0x21B, "AC_Cut": 0x21C, "AC_Paste": 0x21D, "AC_Select_All": 0x21E, "AC_Find": 0x21F, "AC_Find_and_Replace": 0x220, "AC_Search": 0x221, "AC_Go_To": 0x222, "AC_Home": 0x223, "AC_Back": 0x224, "AC_Forward": 0x225, "AC_Stop": 0x226, "AC_Refresh": 0x227, "AC_Previous_Link": 0x228, "AC_Next_Link": 0x229, "AC_Bookmarks": 0x22A, "AC_History": 0x22B, "AC_Subscriptions": 0x22C, "AC_Zoom_In": 0x22D, "AC_Zoom_Out": 0x22E, "AC_Zoom": 0x22F, "AC_Full_Screen_View": 0x230, "AC_Normal_View": 0x231, "AC_View_Toggle": 0x232, "AC_Scroll_Up": 0x233, "AC_Scroll_Down": 0x234, "AC_Scroll": 0x235, "AC_Pan_Left": 0x236, "AC_Pan_Right": 0x237, "AC_Pan": 0x238, "AC_New_Window": 0x239, "AC_Tile_Horizontally": 0x23A, "AC_Tile_Vertically": 0x23B, "AC_Format": 0x23C, "AC_Edit": 0x23D, "AC_Bold": 0x23E, "AC_Italics": 0x23F, "AC_Underline": 0x240, "AC_Strikethrough": 0x241, "AC_Subscript": 0x242, "AC_Superscript": 0x243, "AC_All_Caps": 0x244, "AC_Rotate": 0x245, "AC_Resize": 0x246, "AC_Flip_horizontal": 0x247, "AC_Flip_Vertical": 0x248, "AC_Mirror_Horizontal": 0x249, "AC_Mirror_Vertical": 0x24A, "AC_Font_Select": 0x24B, "AC_Font_Color": 0x24C, "AC_Font_Size": 0x24D, "AC_Justify_Left": 0x24E, "AC_Justify_Center_H": 0x24F, "AC_Justify_Right": 0x250, "AC_Justify_Block_H": 0x251, "AC_Justify_Top": 0x252, "AC_Justify_Center_V": 0x253, "AC_Justify_Bottom": 0x254, "AC_Justify_Block_V": 0x255, "AC_Indent_Decrease": 0x256, "AC_Indent_Increase": 0x257, "AC_Numbered_List": 0x258, "AC_Restart_Numbering": 0x259, "AC_Bulleted_List": 0x25A, "AC_Promote": 0x25B, "AC_Demote": 0x25C, "AC_Yes": 0x25D, "AC_No": 0x25E, "AC_Cancel": 0x25F, "AC_Catalog": 0x260, "AC_Buy__Checkout": 0x261, "AC_Add_to_Cart": 0x262, "AC_Expand": 0x263, "AC_Expand_All": 0x264, "AC_Collapse": 0x265, "AC_Collapse_All": 0x266, "AC_Print_Preview": 0x267, "AC_Paste_Special": 0x268, "AC_Insert_Mode": 0x269, "AC_Delete": 0x26A, "AC_Lock": 0x26B, "AC_Unlock": 0x26C, "AC_Protect": 0x26D, "AC_Unprotect": 0x26E, "AC_Attach_Comment": 0x26F, "AC_Delete_Comment": 0x270, "AC_View_Comment": 0x271, "AC_Select_Word": 0x272, "AC_Select_Sentence": 0x273, "AC_Select_Paragraph": 0x274, "AC_Select_Column": 0x275, "AC_Select_Row": 0x276, "AC_Select_Table": 0x277, "AC_Select_Object": 0x278, "AC_Redo__Repeat": 0x279, "AC_Sort": 0x27A, "AC_Sort_Ascending": 0x27B, "AC_Sort_Descending": 0x27C, "AC_Filter": 0x27D, "AC_Set_Clock": 0x27E, "AC_View_Clock": 0x27F, "AC_Select_Time_Zone": 0x280, "AC_Edit_Time_Zones": 0x281, "AC_Set_Alarm": 0x282, "AC_Clear_Alarm": 0x283, "AC_Snooze_Alarm": 0x284, "AC_Reset_Alarm": 0x285, "AC_Synchronize": 0x286, "AC_Send__Receive": 0x287, "AC_Send_To": 0x288, "AC_Reply": 0x289, "AC_Reply_All": 0x28A, "AC_Forward_Msg": 0x28B, "AC_Send": 0x28C, "AC_Attach_File": 0x28D, "AC_Upload": 0x28E, "AC_Download_Save_Target_As": 0x28F, "AC_Set_Borders": 0x290, "AC_Insert_Row": 0x291, "AC_Insert_Column": 0x292, "AC_Insert_File": 0x293, "AC_Insert_Picture": 0x294, "AC_Insert_Object": 0x295, "AC_Insert_Symbol": 0x296, "AC_Save_and_Close": 0x297, "AC_Rename": 0x298, "AC_Merge": 0x299, "AC_Split": 0x29A, "AC_Distribute_Horizontally": 0x29B, "AC_Distribute_Vertically": 0x29C, } ) HID_CONSUMERCODES[0x20] = "+10" HID_CONSUMERCODES[0x21] = "+100" HID_CONSUMERCODES._fallback = lambda x: f"unknown:{x:04X}" ## Information for x1c00 Persistent from https://drive.google.com/drive/folders/0BxbRzx7vEV7eWmgwazJ3NUFfQ28 KEYMOD = NamedInts(CTRL=0x01, SHIFT=0x02, ALT=0x04, META=0x08, RCTRL=0x10, RSHIFT=0x20, RALT=0x40, RMETA=0x80) ACTIONID = NamedInts( Empty=0x00, Key=0x01, Mouse=0x02, Xdisp=0x03, Ydisp=0x04, Vscroll=0x05, Hscroll=0x06, Consumer=0x07, Internal=0x08, Power=0x09, ) MOUSE_BUTTONS = NamedInts( Mouse_Button_Left=0x0001, Mouse_Button_Right=0x0002, Mouse_Button_Middle=0x0004, Mouse_Button_Back=0x0008, Mouse_Button_Forward=0x0010, Mouse_Button_6=0x0020, Mouse_Button_Scroll_Left=0x0040, Mouse_Button_Scroll_Right=0x0080, Mouse_Button_9=0x0100, Mouse_Button_10=0x0200, Mouse_Button_11=0x0400, Mouse_Button_12=0x0800, Mouse_Button_13=0x1000, Mouse_Button_DPI=0x2000, Mouse_Button_15=0x4000, Mouse_Button_16=0x8000, ) MOUSE_BUTTONS._fallback = lambda x: f"unknown mouse button:{x:04X}" HORIZONTAL_SCROLL = NamedInts( Horizontal_Scroll_Left=0x4000, Horizontal_Scroll_Right=0x8000, ) HORIZONTAL_SCROLL._fallback = lambda x: f"unknown horizontal scroll:{x:04X}" # Construct universe for Persistent Remappable Keys setting (only for supported values) KEYS = UnsortedNamedInts() KEYS_Default = 0x7FFFFFFF # Special value to reset key to default - has to be different from all others KEYS[KEYS_Default] = "Default" # Value to reset to default KEYS[0] = "None" # Value for no output # Add HID keys plus modifiers modifiers = { 0x00: "", 0x01: "Cntrl+", 0x02: "Shift+", 0x04: "Alt+", 0x08: "Meta+", 0x03: "Cntrl+Shift+", 0x05: "Alt+Cntrl+", 0x09: "Meta+Cntrl+", 0x06: "Alt+Shift+", 0x0A: "Meta+Shift+", 0x0C: "Meta+Alt+", } for val, name in modifiers.items(): for key in USB_HID_KEYCODES: KEYS[(ACTIONID.Key << 24) + (int(key) << 8) + val] = name + str(key) # Add HID Consumer Codes for code in HID_CONSUMERCODES: KEYS[(ACTIONID.Consumer << 24) + (int(code) << 8)] = str(code) # Add Mouse Buttons for code in MOUSE_BUTTONS: KEYS[(ACTIONID.Mouse << 24) + (int(code) << 8)] = str(code) # Add Horizontal Scroll for code in HORIZONTAL_SCROLL: KEYS[(ACTIONID.Hscroll << 24) + (int(code) << 8)] = str(code) # Construct subsets for known devices def persistent_keys(action_ids): keys = UnsortedNamedInts() keys[KEYS_Default] = "Default" # Value to reset to default keys[0] = "No Output (only as default)" for key in KEYS: if (int(key) >> 24) in action_ids: keys[int(key)] = str(key) return keys KEYS_KEYS_CONSUMER = persistent_keys([ACTIONID.Key, ACTIONID.Consumer]) KEYS_KEYS_MOUSE_HSCROLL = persistent_keys([ACTIONID.Key, ACTIONID.Mouse, ACTIONID.Hscroll]) COLORS = UnsortedNamedInts( { # from Xorg rgb.txt,v 1.3 2000/08/17 "red": 0xFF0000, "orange": 0xFFA500, "yellow": 0xFFFF00, "green": 0x00FF00, "blue": 0x0000FF, "purple": 0xA020F0, "violet": 0xEE82EE, "black": 0x000000, "white": 0xFFFFFF, "gray": 0xBEBEBE, "brown": 0xA52A2A, "cyan": 0x00FFFF, "magenta": 0xFF00FF, "pink": 0xFFC0CB, "maroon": 0xB03060, "turquoise": 0x40E0D0, "gold": 0xFFD700, "tan": 0xD2B48C, "snow": 0xFFFAFA, "ghost white": 0xF8F8FF, "white smoke": 0xF5F5F5, "gainsboro": 0xDCDCDC, "floral white": 0xFFFAF0, "old lace": 0xFDF5E6, "linen": 0xFAF0E6, "antique white": 0xFAEBD7, "papaya whip": 0xFFEFD5, "blanched almond": 0xFFEBCD, "bisque": 0xFFE4C4, "peach puff": 0xFFDAB9, "navajo white": 0xFFDEAD, "moccasin": 0xFFE4B5, "cornsilk": 0xFFF8DC, "ivory": 0xFFFFF0, "lemon chiffon": 0xFFFACD, "seashell": 0xFFF5EE, "honeydew": 0xF0FFF0, "mint cream": 0xF5FFFA, "azure": 0xF0FFFF, "alice blue": 0xF0F8FF, "lavender": 0xE6E6FA, "lavender blush": 0xFFF0F5, "misty rose": 0xFFE4E1, "dark slate gray": 0x2F4F4F, "dim gray": 0x696969, "slate gray": 0x708090, "light slate gray": 0x778899, "light gray": 0xD3D3D3, "midnight blue": 0x191970, "navy blue": 0x000080, "cornflower blue": 0x6495ED, "dark slate blue": 0x483D8B, "slate blue": 0x6A5ACD, "medium slate blue": 0x7B68EE, "light slate blue": 0x8470FF, "medium blue": 0x0000CD, "royal blue": 0x4169E1, "dodger blue": 0x1E90FF, "deep sky blue": 0x00BFFF, "sky blue": 0x87CEEB, "light sky blue": 0x87CEFA, "steel blue": 0x4682B4, "light steel blue": 0xB0C4DE, "light blue": 0xADD8E6, "powder blue": 0xB0E0E6, "pale turquoise": 0xAFEEEE, "dark turquoise": 0x00CED1, "medium turquoise": 0x48D1CC, "light cyan": 0xE0FFFF, "cadet blue": 0x5F9EA0, "medium aquamarine": 0x66CDAA, "aquamarine": 0x7FFFD4, "dark green": 0x006400, "dark olive green": 0x556B2F, "dark sea green": 0x8FBC8F, "sea green": 0x2E8B57, "medium sea green": 0x3CB371, "light sea green": 0x20B2AA, "pale green": 0x98FB98, "spring green": 0x00FF7F, "lawn green": 0x7CFC00, "chartreuse": 0x7FFF00, "medium spring green": 0x00FA9A, "green yellow": 0xADFF2F, "lime green": 0x32CD32, "yellow green": 0x9ACD32, "forest green": 0x228B22, "olive drab": 0x6B8E23, "dark khaki": 0xBDB76B, "khaki": 0xF0E68C, "pale goldenrod": 0xEEE8AA, "light goldenrod yellow": 0xFAFAD2, "light yellow": 0xFFFFE0, "light goldenrod": 0xEEDD82, "goldenrod": 0xDAA520, "dark goldenrod": 0xB8860B, "rosy brown": 0xBC8F8F, "indian red": 0xCD5C5C, "saddle brown": 0x8B4513, "sienna": 0xA0522D, "peru": 0xCD853F, "burlywood": 0xDEB887, "beige": 0xF5F5DC, "wheat": 0xF5DEB3, "sandy brown": 0xF4A460, "chocolate": 0xD2691E, "firebrick": 0xB22222, "dark salmon": 0xE9967A, "salmon": 0xFA8072, "light salmon": 0xFFA07A, "dark orange": 0xFF8C00, "coral": 0xFF7F50, "light coral": 0xF08080, "tomato": 0xFF6347, "orange red": 0xFF4500, "hot pink": 0xFF69B4, "deep pink": 0xFF1493, "light pink": 0xFFB6C1, "pale violet red": 0xDB7093, "medium violet red": 0xC71585, "violet red": 0xD02090, "plum": 0xDDA0DD, "orchid": 0xDA70D6, "medium orchid": 0xBA55D3, "dark orchid": 0x9932CC, "dark violet": 0x9400D3, "blue violet": 0x8A2BE2, "medium purple": 0x9370DB, "thistle": 0xD8BFD8, "dark gray": 0xA9A9A9, "dark blue": 0x00008B, "dark cyan": 0x008B8B, "dark magenta": 0x8B008B, "dark red": 0x8B0000, "light green": 0x90EE90, } ) COLORSPLUS = UnsortedNamedInts({"No change": -1}) for i in COLORS: COLORSPLUS[int(i)] = str(i) KEYCODES = NamedInts( { "A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6, "G": 7, "H": 8, "I": 9, "J": 10, "K": 11, "L": 12, "M": 13, "N": 14, "O": 15, "P": 16, "Q": 17, "R": 18, "S": 19, "T": 20, "U": 21, "V": 22, "W": 23, "X": 24, "Y": 25, "Z": 26, "1": 27, "2": 28, "3": 29, "4": 30, "5": 31, "6": 32, "7": 33, "8": 34, "9": 35, "0": 36, "ENTER": 37, "ESC": 38, "BACKSPACE": 39, "TAB": 40, "SPACE": 41, "-": 42, "=": 43, "[": 44, "]": 45, "\\": 45, "~": 47, ";": 48, "'": 49, "`": 50, ",": 51, ".": 52, "/": 53, "CAPS LOCK": 54, "F1": 55, "F2": 56, "F3": 57, "F4": 58, "F5": 59, "F6": 60, "F7": 61, "F8": 62, "F9": 63, "F10": 64, "F11": 65, "F12": 66, "PRINT": 67, "SCROLL LOCK": 68, "PASTE": 69, "INSERT": 70, "HOME": 71, "PAGE UP": 72, "DELETE": 73, "END": 74, "PAGE DOWN": 75, "RIGHT": 76, "LEFT": 77, "DOWN": 78, "UP": 79, "NUMLOCK": 80, "KEYPAD /": 81, "KEYPAD *": 82, "KEYPAD -": 83, "KEYPAD +": 84, "KEYPAD ENTER": 85, "KEYPAD 1": 86, "KEYPAD 2": 87, "KEYPAD 3": 88, "KEYPAD 4": 89, "KEYPAD 5": 90, "KEYPAD 6": 91, "KEYPAD 7": 92, "KEYPAD 8": 93, "KEYPAD 9": 94, "KEYPAD 0": 95, "KEYPAD .": 96, "COMPOSE": 98, "POWER": 99, "LEFT CTRL": 104, "LEFT SHIFT": 105, "LEFT ALT": 106, "LEFT WINDOWS": 107, "RIGHT CTRL": 108, "RIGHT SHIFT": 109, "RIGHT ALTGR": 110, "RIGHT WINDOWS": 111, "BRIGHTNESS": 153, "PAUSE": 155, "MUTE": 156, "NEXT": 157, "PREVIOUS": 158, "G1": 180, "G2": 181, "G3": 182, "G4": 183, "G5": 184, "LOGO": 210, } ) # load in override dictionary for KEYCODES try: if os.path.isfile(_keys_file_path): with open(_keys_file_path) as keys_file: keys = yaml.safe_load(keys_file) if isinstance(keys, dict): keys = NamedInts(**keys) for k in KEYCODES: if int(k) not in keys and str(k) not in keys: keys[int(k)] = str(k) KEYCODES = keys except Exception as e: print(e)
47,936
Python
.py
1,529
24.158273
123
0.593444
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,460
listener.py
pwr-Solaar_Solaar/lib/logitech_receiver/listener.py
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/ ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import logging import queue import threading from . import base from . import exceptions logger = logging.getLogger(__name__) class _ThreadedHandle: """A thread-local wrapper with different open handles for each thread. Closing a ThreadedHandle will close all handles. """ __slots__ = ("path", "_local", "_handles", "_listener") def __init__(self, listener, path, handle): assert listener is not None assert path is not None assert handle is not None assert isinstance(handle, int) self._listener = listener self.path = path self._local = threading.local() # take over the current handle for the thread doing the replacement self._local.handle = handle self._handles = [handle] def _open(self): handle = base.open_path(self.path) if handle is None: logger.error("%r failed to open new handle", self) else: # if logger.isEnabledFor(logging.DEBUG): # logger.debug("%r opened new handle %d", self, handle) self._local.handle = handle self._handles.append(handle) return handle def close(self): if self._local: self._local = None handles, self._handles = self._handles, [] if logger.isEnabledFor(logging.DEBUG): logger.debug("%r closing %s", self, handles) for h in handles: base.close(h) @property def notifications_hook(self): if self._listener: assert isinstance(self._listener, threading.Thread) if threading.current_thread() == self._listener: return self._listener._notifications_hook def __del__(self): self._listener = None self.close() def __index__(self): if self._local: try: return self._local.handle except Exception: return self._open() else: return -1 __int__ = __index__ def __str__(self): if self._local: return str(int(self)) def __repr__(self): return f"<_ThreadedHandle({self.path})>" def __bool__(self): return bool(self._local) __nonzero__ = __bool__ # How long to wait during a read for the next packet, in seconds. # Ideally this should be rather long (10s ?), but the read is blocking and this means that when the thread # is signalled to stop, it would take a while for it to acknowledge it. # Forcibly closing the file handle on another thread does _not_ interrupt the read on Linux systems. _EVENT_READ_TIMEOUT = 1.0 # in seconds class EventsListener(threading.Thread): """Listener thread for notifications from the Unifying Receiver. Incoming packets will be passed to the callback function in sequence. """ def __init__(self, receiver, notifications_callback): try: path_name = receiver.path.split("/")[2] except IndexError: path_name = receiver.path super().__init__(name=self.__class__.__name__ + ":" + path_name) self.daemon = True self._active = False self.receiver = receiver self._queued_notifications = queue.Queue(16) self._notifications_callback = notifications_callback def run(self): self._active = True # replace the handle with a threaded one self.receiver.handle = _ThreadedHandle(self, self.receiver.path, self.receiver.handle) if logger.isEnabledFor(logging.INFO): logger.info("started with %s (%d)", self.receiver, int(self.receiver.handle)) self.has_started() if self.receiver.isDevice: # ping (wired or BT) devices to see if they are really online if self.receiver.ping(): self.receiver.changed(active=True, reason="initialization") while self._active: if self._queued_notifications.empty(): try: n = base.read(self.receiver.handle, _EVENT_READ_TIMEOUT) except exceptions.NoReceiver: logger.warning("%s disconnected", self.receiver.name) self.receiver.close() break if n: n = base.make_notification(*n) else: n = self._queued_notifications.get() # deliver any queued notifications if n: try: self._notifications_callback(n) except Exception: logger.exception("processing %s", n) del self._queued_notifications self.has_stopped() def stop(self): """Tells the listener to stop as soon as possible.""" self._active = False def has_started(self): """Called right after the thread has started, and before it starts reading notification packets.""" pass def has_stopped(self): """Called right before the thread stops.""" pass def _notifications_hook(self, n): # Only consider unhandled notifications that were sent from this thread, # i.e. triggered by a callback handling a previous notification. assert threading.current_thread() == self if self._active: # and threading.current_thread() == self: # if logger.isEnabledFor(logging.DEBUG): # logger.debug("queueing unhandled %s", n) if not self._queued_notifications.full(): self._queued_notifications.put(n) def __bool__(self): return bool(self._active and self.receiver) __nonzero__ = __bool__
6,552
Python
.py
153
33.921569
106
0.623783
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,461
desktop_notifications.py
pwr-Solaar_Solaar/lib/logitech_receiver/desktop_notifications.py
## Copyright (C) 2024 Solaar contributors ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """Implements the desktop notification service.""" import importlib import logging logger = logging.getLogger(__name__) def notifications_available(): """Checks if notification service is available.""" notifications_supported = False try: import gi gi.require_version("Notify", "0.7") gi.require_version("Gtk", "3.0") importlib.util.find_spec("gi.repository.GLib") importlib.util.find_spec("gi.repository.Gtk") importlib.util.find_spec("gi.repository.Notify") notifications_supported = True except ValueError as e: logger.warning(f"Notification service is not available: {e}") return notifications_supported available = notifications_available() if available: from gi.repository import GLib from gi.repository import Gtk from gi.repository import Notify # cache references to shown notifications here to allow reuse _notifications = {} _ICON_LISTS = {} def init(): """Initialize desktop notifications.""" global available if available: if not Notify.is_initted(): if logger.isEnabledFor(logging.INFO): logger.info("starting desktop notifications") try: return Notify.init("solaar") # replace with better name later except Exception: logger.exception("initializing desktop notifications") available = False return available and Notify.is_initted() def uninit(): """Stop desktop notifications.""" if available and Notify.is_initted(): if logger.isEnabledFor(logging.INFO): logger.info("stopping desktop notifications") _notifications.clear() Notify.uninit() def show(dev, message: str, icon=None): """Show a notification with title and text.""" if available and (Notify.is_initted() or init()): summary = dev.name n = _notifications.get(summary) # reuse notification of same name if n is None: n = _notifications[summary] = Notify.Notification() icon_name = device_icon_name(dev.name, dev.kind) if icon is None else icon n.update(summary, message, icon_name) n.set_urgency(Notify.Urgency.NORMAL) n.set_hint("desktop-entry", GLib.Variant("s", "solaar")) # replace with better name late try: n.show() except Exception: logger.exception(f"showing {n}") def device_icon_list(name="_", kind=None): icon_list = _ICON_LISTS.get(name) if icon_list is None: # names of possible icons, in reverse order of likelihood # the theme will hopefully pick up the most appropriate icon_list = ["preferences-desktop-peripherals"] kind = str(kind) if kind: if kind == "numpad": icon_list += ("input-keyboard", "input-dialpad") elif kind == "touchpad": icon_list += ("input-mouse", "input-tablet") elif kind == "trackball": icon_list += ("input-mouse",) elif kind == "headset": icon_list += ("audio-headphones", "audio-headset") icon_list += (f"input-{kind}",) _ICON_LISTS[name] = icon_list return icon_list def device_icon_name(name, kind=None): _default_theme = Gtk.IconTheme.get_default() icon_list = device_icon_list(name, kind) for n in reversed(icon_list): if _default_theme.has_icon(n): return n else: def init(): return False def uninit(): return None def show(dev, reason=None): return None
4,647
Python
.py
108
33.648148
101
0.62085
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,462
i18n.py
pwr-Solaar_Solaar/lib/logitech_receiver/i18n.py
## Copyright (C) 2012-2013 Daniel Pavel ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # Translation support for the Logitech receivers library import gettext _ = gettext.gettext ngettext = gettext.ngettext # A few common strings, not always accessible as such in the code. _DUMMY = ( # approximative battery levels _("empty"), _("critical"), _("low"), _("average"), _("good"), _("full"), # battery charging statuses _("discharging"), _("recharging"), _("charging"), _("not charging"), _("almost full"), _("charged"), _("slow recharge"), _("invalid battery"), _("thermal error"), _("error"), _("standard"), _("fast"), _("slow"), # pairing errors _("device timeout"), _("device not supported"), _("too many devices"), _("sequence timeout"), # firmware kinds _("Firmware"), _("Bootloader"), _("Hardware"), _("Other"), # common button and task names (from special_keys.py) _("Left Button"), _("Right Button"), _("Middle Button"), _("Back Button"), _("Forward Button"), _("Mouse Gesture Button"), _("Smart Shift"), _("DPI Switch"), _("Left Tilt"), _("Right Tilt"), _("Left Click"), _("Right Click"), _("Mouse Middle Button"), _("Mouse Back Button"), _("Mouse Forward Button"), _("Gesture Button Navigation"), _("Mouse Scroll Left Button"), _("Mouse Scroll Right Button"), # key/button statuses _("pressed"), _("released"), )
2,212
Python
.py
75
25.6
74
0.636492
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,463
__init__.py
pwr-Solaar_Solaar/lib/logitech_receiver/__init__.py
## Copyright (C) 2012-2013 Daniel Pavel ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """Low-level interface for devices using Logitech HID++ protocol. Uses the HID api exposed through hidapi_impl.py, a Python thin layer over a native implementation. """ import logging logger = logging.getLogger(__name__)
985
Python
.py
21
45.761905
82
0.772112
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,464
base_usb.py
pwr-Solaar_Solaar/lib/logitech_receiver/base_usb.py
## Copyright (C) 2012-2013 Daniel Pavel ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """Collection of known Logitech product IDs. According to Logitech, they use the following product IDs (as of September 2020) USB product IDs for receivers: 0xC526 - 0xC5xx Wireless PIDs for hidpp10 devices: 0x2006 - 0x2019 Wireless PIDs for hidpp20 devices: 0x4002 - 0x4097, 0x4101 - 0x4102 USB product IDs for hidpp20 devices: 0xC07D - 0xC094, 0xC32B - 0xC344 Bluetooth product IDs (for hidpp20 devices): 0xB012 - 0xB0xx, 0xB32A - 0xB3xx USB ids of Logitech wireless receivers. Only receivers supporting the HID++ protocol can go in here. """ from solaar.i18n import _ # max_devices is only used for receivers that do not support reading from Registers.RECEIVER_INFO offset 0x03, default # to 1. # may_unpair is only used for receivers that do not support reading from Registers.RECEIVER_INFO offset 0x03, # default to False. # unpair is for receivers that do support reading from Registers.RECEIVER_INFO offset 0x03, no default. ## should this last be changed so that may_unpair is used for all receivers? writing to Registers.RECEIVER_PAIRING ## doesn't seem right LOGITECH_VENDOR_ID = 0x046D def _bolt_receiver(product_id: int) -> dict: return { "vendor_id": LOGITECH_VENDOR_ID, "product_id": product_id, "usb_interface": 2, "name": _("Bolt Receiver"), "receiver_kind": "bolt", "max_devices": 6, "may_unpair": True, } def _unifying_receiver(product_id: int) -> dict: return { "vendor_id": LOGITECH_VENDOR_ID, "product_id": product_id, "usb_interface": 2, "name": _("Unifying Receiver"), "receiver_kind": "unifying", "may_unpair": True, } def _nano_receiver(product_id: int) -> dict: return { "vendor_id": LOGITECH_VENDOR_ID, "product_id": product_id, "usb_interface": 1, "name": _("Nano Receiver"), "receiver_kind": "nano", "may_unpair": False, "re_pairs": True, } def _nano_receiver_no_unpair(product_id: int) -> dict: return { "vendor_id": LOGITECH_VENDOR_ID, "product_id": product_id, "usb_interface": 1, "name": _("Nano Receiver"), "receiver_kind": "nano", "may_unpair": False, "unpair": False, "re_pairs": True, } def _nano_receiver_max2(product_id: int) -> dict: return { "vendor_id": LOGITECH_VENDOR_ID, "product_id": product_id, "usb_interface": 1, "name": _("Nano Receiver"), "receiver_kind": "nano", "max_devices": 2, "may_unpair": False, "re_pairs": True, } def _lenovo_receiver(product_id: int) -> dict: return { "vendor_id": 6127, "product_id": product_id, "usb_interface": 1, "name": _("Nano Receiver"), "receiver_kind": "nano", "may_unpair": False, } def _lightspeed_receiver(product_id: int) -> dict: return { "vendor_id": LOGITECH_VENDOR_ID, "product_id": product_id, "usb_interface": 2, "receiver_kind": "lightspeed", "name": _("Lightspeed Receiver"), "may_unpair": False, } def _ex100_receiver(product_id: int) -> dict: return { "vendor_id": LOGITECH_VENDOR_ID, "product_id": product_id, "usb_interface": 1, "name": _("EX100 Receiver 27 Mhz"), "receiver_kind": "27Mhz", "max_devices": 4, "may_unpair": False, "re_pairs": True, } # Receivers added here should also be listed in # share/solaar/io.github.pwr_solaar.solaar.meta-info.xml # Look in https://github.com/torvalds/linux/blob/master/drivers/hid/hid-ids.h # Bolt receivers (marked with the yellow lightning bolt logo) BOLT_RECEIVER_C548 = _bolt_receiver(0xC548) # standard Unifying receivers (marked with the orange Unifying logo) UNIFYING_RECEIVER_C52B = _unifying_receiver(0xC52B) UNIFYING_RECEIVER_C532 = _unifying_receiver(0xC532) # Nano receivers (usually sold with low-end devices) NANO_RECEIVER_ADVANCED = _nano_receiver_no_unpair(0xC52F) NANO_RECEIVER_C518 = _nano_receiver(0xC518) NANO_RECEIVER_C51A = _nano_receiver(0xC51A) NANO_RECEIVER_C51B = _nano_receiver(0xC51B) NANO_RECEIVER_C521 = _nano_receiver(0xC521) NANO_RECEIVER_C525 = _nano_receiver(0xC525) NANO_RECEIVER_C526 = _nano_receiver(0xC526) NANO_RECEIVER_C52E = _nano_receiver_no_unpair(0xC52E) NANO_RECEIVER_C531 = _nano_receiver(0xC531) NANO_RECEIVER_C534 = _nano_receiver_max2(0xC534) NANO_RECEIVER_C535 = _nano_receiver(0xC535) # branded as Dell NANO_RECEIVER_C537 = _nano_receiver(0xC537) NANO_RECEIVER_6042 = _lenovo_receiver(0x6042) # Lightspeed receivers (usually sold with gaming devices) LIGHTSPEED_RECEIVER_C539 = _lightspeed_receiver(0xC539) LIGHTSPEED_RECEIVER_C53A = _lightspeed_receiver(0xC53A) LIGHTSPEED_RECEIVER_C53D = _lightspeed_receiver(0xC53D) LIGHTSPEED_RECEIVER_C53F = _lightspeed_receiver(0xC53F) LIGHTSPEED_RECEIVER_C541 = _lightspeed_receiver(0xC541) LIGHTSPEED_RECEIVER_C545 = _lightspeed_receiver(0xC545) LIGHTSPEED_RECEIVER_C547 = _lightspeed_receiver(0xC547) # EX100 old style receiver pre-unifying protocol EX100_27MHZ_RECEIVER_C517 = _ex100_receiver(0xC517) KNOWN_RECEIVERS = ( BOLT_RECEIVER_C548, UNIFYING_RECEIVER_C52B, UNIFYING_RECEIVER_C532, NANO_RECEIVER_ADVANCED, NANO_RECEIVER_C518, NANO_RECEIVER_C51A, NANO_RECEIVER_C51B, NANO_RECEIVER_C521, NANO_RECEIVER_C525, NANO_RECEIVER_C526, NANO_RECEIVER_C52E, NANO_RECEIVER_C531, NANO_RECEIVER_C534, NANO_RECEIVER_C535, NANO_RECEIVER_C537, NANO_RECEIVER_6042, LIGHTSPEED_RECEIVER_C539, LIGHTSPEED_RECEIVER_C53A, LIGHTSPEED_RECEIVER_C53D, LIGHTSPEED_RECEIVER_C53F, LIGHTSPEED_RECEIVER_C541, LIGHTSPEED_RECEIVER_C545, LIGHTSPEED_RECEIVER_C547, EX100_27MHZ_RECEIVER_C517, ) def get_receiver_info(product_id: int) -> dict: """Returns hardcoded information about Logitech receiver. Parameters ---------- product_id Product ID of receiver e.g. 0xC548 for a Logitech Bolt receiver. Returns ------- dict Product info with mandatory vendor_id, product_id, usb_interface, name, receiver_kind """ for receiver in KNOWN_RECEIVERS: if product_id == receiver.get("product_id"): return receiver raise ValueError(f"Unknown product ID '0x{product_id:02X}")
7,160
Python
.py
188
33.223404
118
0.693283
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,465
hidpp10.py
pwr-Solaar_Solaar/lib/logitech_receiver/hidpp10.py
## Copyright (C) 2012-2013 Daniel Pavel ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from __future__ import annotations import logging from typing import Any from typing_extensions import Protocol from . import common from .common import Battery from .common import BatteryLevelApproximation from .common import BatteryStatus from .common import FirmwareKind from .hidpp10_constants import Registers logger = logging.getLogger(__name__) class Device(Protocol): def request(self, request_id, *params): ... @property def kind(self) -> Any: ... @property def online(self) -> bool: ... @property def protocol(self) -> Any: ... @property def registers(self) -> list: ... def read_register(device: Device, register: Registers | int, *params) -> Any: assert device is not None, f"tried to read register {register:02X} from invalid device {device}" # support long registers by adding a 2 in front of the register number request_id = 0x8100 | (int(register) & 0x2FF) return device.request(request_id, *params) def write_register(device: Device, register: Registers | int, *value) -> Any: assert device is not None, f"tried to write register {register:02X} to invalid device {device}" # support long registers by adding a 2 in front of the register number request_id = 0x8000 | (int(register) & 0x2FF) return device.request(request_id, *value) def get_configuration_pending_flags(receiver): assert not receiver.isDevice result = read_register(receiver, Registers.DEVICES_CONFIGURATION) if result is not None: return ord(result[:1]) def set_configuration_pending_flags(receiver, devices): assert not receiver.isDevice result = write_register(receiver, Registers.DEVICES_CONFIGURATION, devices) return result is not None class Hidpp10: def get_battery(self, device: Device): assert device is not None assert device.kind is not None if not device.online: return """Reads a device's battery level, if provided by the HID++ 1.0 protocol.""" if device.protocol and device.protocol >= 2.0: # let's just assume HID++ 2.0 devices do not provide the battery info in a register return for r in (Registers.BATTERY_STATUS, Registers.BATTERY_CHARGE): if r in device.registers: reply = read_register(device, r) if reply: return parse_battery_status(r, reply) return # the descriptor does not tell us which register this device has, try them both reply = read_register(device, Registers.BATTERY_CHARGE) if reply: # remember this for the next time device.registers.append(Registers.BATTERY_CHARGE) return parse_battery_status(Registers.BATTERY_CHARGE, reply) reply = read_register(device, Registers.BATTERY_STATUS) if reply: # remember this for the next time device.registers.append(Registers.BATTERY_STATUS) return parse_battery_status(Registers.BATTERY_STATUS, reply) def get_firmware(self, device: Device) -> tuple[common.FirmwareInfo] | None: assert device is not None firmware = [None, None, None] reply = read_register(device, Registers.FIRMWARE, 0x01) if not reply: # won't be able to read any of it now... return fw_version = common.strhex(reply[1:3]) fw_version = f"{fw_version[0:2]}.{fw_version[2:4]}" reply = read_register(device, Registers.FIRMWARE, 0x02) if reply: fw_version += ".B" + common.strhex(reply[1:3]) fw = common.FirmwareInfo(FirmwareKind.Firmware, "", fw_version, None) firmware[0] = fw reply = read_register(device, Registers.FIRMWARE, 0x04) if reply: bl_version = common.strhex(reply[1:3]) bl_version = f"{bl_version[0:2]}.{bl_version[2:4]}" bl = common.FirmwareInfo(FirmwareKind.Bootloader, "", bl_version, None) firmware[1] = bl reply = read_register(device, Registers.FIRMWARE, 0x03) if reply: o_version = common.strhex(reply[1:3]) o_version = f"{o_version[0:2]}.{o_version[2:4]}" o = common.FirmwareInfo(FirmwareKind.Other, "", o_version, None) firmware[2] = o if any(firmware): return tuple(f for f in firmware if f) def set_3leds(self, device: Device, battery_level=None, charging=None, warning=None): assert device is not None assert device.kind is not None if not device.online: return if Registers.THREE_LEDS not in device.registers: return if battery_level is not None: if battery_level < BatteryLevelApproximation.CRITICAL: # 1 orange, and force blink v1, v2 = 0x22, 0x00 warning = True elif battery_level < BatteryLevelApproximation.LOW: # 1 orange v1, v2 = 0x22, 0x00 elif battery_level < BatteryLevelApproximation.GOOD: # 1 green v1, v2 = 0x20, 0x00 elif battery_level < BatteryLevelApproximation.FULL: # 2 greens v1, v2 = 0x20, 0x02 else: # all 3 green v1, v2 = 0x20, 0x22 if warning: # set the blinking flag for the leds already set v1 |= v1 >> 1 v2 |= v2 >> 1 elif charging: # blink all green v1, v2 = 0x30, 0x33 elif warning: # 1 red v1, v2 = 0x02, 0x00 else: # turn off all leds v1, v2 = 0x11, 0x11 write_register(device, Registers.THREE_LEDS, v1, v2) def get_notification_flags(self, device: Device): return self._get_register(device, Registers.NOTIFICATIONS) def set_notification_flags(self, device: Device, *flag_bits): assert device is not None # Avoid a call if the device is not online, # or the device does not support registers. if device.kind is not None: # peripherals with protocol >= 2.0 don't support registers if device.protocol and device.protocol >= 2.0: return flag_bits = sum(int(b) for b in flag_bits) assert flag_bits & 0x00FFFFFF == flag_bits result = write_register(device, Registers.NOTIFICATIONS, common.int2bytes(flag_bits, 3)) return result is not None def get_device_features(self, device: Device): return self._get_register(device, Registers.MOUSE_BUTTON_FLAGS) def _get_register(self, device: Device, register: Registers | int): assert device is not None # Avoid a call if the device is not online, # or the device does not support registers. if device.kind is not None: # peripherals with protocol >= 2.0 don't support registers if device.protocol and device.protocol >= 2.0: return flags = read_register(device, register) if flags is not None: assert len(flags) == 3 return common.bytes2int(flags) def parse_battery_status(register: Registers | int, reply) -> Battery | None: def status_byte_to_charge(status_byte_: int) -> BatteryLevelApproximation: if status_byte_ == 7: charge_ = BatteryLevelApproximation.FULL elif status_byte_ == 5: charge_ = BatteryLevelApproximation.GOOD elif status_byte_ == 3: charge_ = BatteryLevelApproximation.LOW elif status_byte_ == 1: charge_ = BatteryLevelApproximation.CRITICAL else: # pure 'charging' notifications may come without a status charge_ = BatteryLevelApproximation.EMPTY return charge_ def status_byte_to_battery_status(status_byte_: int) -> BatteryStatus: if status_byte_ == 0x30: status_text_ = BatteryStatus.DISCHARGING elif status_byte_ == 0x50: status_text_ = BatteryStatus.RECHARGING elif status_byte_ == 0x90: status_text_ = BatteryStatus.FULL else: status_text_ = None return status_text_ def charging_byte_to_status_text(charging_byte_: int) -> BatteryStatus: if charging_byte_ == 0x00: status_text_ = BatteryStatus.DISCHARGING elif charging_byte_ & 0x21 == 0x21: status_text_ = BatteryStatus.RECHARGING elif charging_byte_ & 0x22 == 0x22: status_text_ = BatteryStatus.FULL else: logger.warning("could not parse 0x07 battery status: %02X (level %02X)", charging_byte_, status_byte) status_text_ = None return status_text_ if register == Registers.BATTERY_CHARGE: charge = ord(reply[:1]) status_byte = ord(reply[2:3]) & 0xF0 battery_status = status_byte_to_battery_status(status_byte) return Battery(charge, None, battery_status, None) if register == Registers.BATTERY_STATUS: status_byte = ord(reply[:1]) charging_byte = ord(reply[1:2]) status_text = charging_byte_to_status_text(charging_byte) charge = status_byte_to_charge(status_byte) if charging_byte & 0x03 and status_byte == 0: # some 'charging' notifications may come with no battery level information charge = None # Return None for next charge level and voltage as these are not in HID++ 1.0 spec return Battery(charge, None, status_text, None)
10,484
Python
.py
231
36.17316
113
0.636765
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,466
hidpp10_constants.py
pwr-Solaar_Solaar/lib/logitech_receiver/hidpp10_constants.py
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/ ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from enum import IntEnum from .common import NamedInts """HID constants for HID++ 1.0. Most of them as defined by the official Logitech HID++ 1.0 documentation, some of them guessed. """ DEVICE_KIND = NamedInts( unknown=0x00, keyboard=0x01, mouse=0x02, numpad=0x03, presenter=0x04, remote=0x07, trackball=0x08, touchpad=0x09, tablet=0x0A, gamepad=0x0B, joystick=0x0C, headset=0x0D, # not from Logitech documentation remote_control=0x0E, # for compatibility with HID++ 2.0 receiver=0x0F, # for compatibility with HID++ 2.0 ) POWER_SWITCH_LOCATION = NamedInts( base=0x01, top_case=0x02, edge_of_top_right_corner=0x03, top_left_corner=0x05, bottom_left_corner=0x06, top_right_corner=0x07, bottom_right_corner=0x08, top_edge=0x09, right_edge=0x0A, left_edge=0x0B, bottom_edge=0x0C, ) # Some flags are used both by devices and receivers. The Logitech documentation # mentions that the first and last (third) byte are used for devices while the # second is used for the receiver. In practise, the second byte is also used for # some device-specific notifications (keyboard illumination level). Do not # simply set all notification bits if the software does not support it. For # example, enabling keyboard_sleep_raw makes the Sleep key a no-operation unless # the software is updated to handle that event. # Observations: # - wireless and software present were seen on receivers, reserved_r1b4 as well # - the rest work only on devices as far as we can tell right now # In the future would be useful to have separate enums for receiver and device notification flags, # but right now we don't know enough. # additional flags taken from https://drive.google.com/file/d/0BxbRzx7vEV7eNDBheWY0UHM5dEU/view?usp=sharing NOTIFICATION_FLAG = NamedInts( numpad_numerical_keys=0x800000, f_lock_status=0x400000, roller_H=0x200000, battery_status=0x100000, # send battery charge notifications (0x07 or 0x0D) mouse_extra_buttons=0x080000, roller_V=0x040000, power_keys=0x020000, # system control keys such as Sleep keyboard_multimedia_raw=0x010000, # consumer controls such as Mute and Calculator multi_touch=0x001000, # notify on multi-touch changes software_present=0x000800, # software is controlling part of device behaviour link_quality=0x000400, # notify on link quality changes ui=0x000200, # notify on UI changes wireless=0x000100, # notify when the device wireless goes on/off-line configuration_complete=0x000004, voip_telephony=0x000002, threed_gesture=0x000001, ) ERROR = NamedInts( invalid_SubID__command=0x01, invalid_address=0x02, invalid_value=0x03, connection_request_failed=0x04, too_many_devices=0x05, already_exists=0x06, busy=0x07, unknown_device=0x08, resource_error=0x09, request_unavailable=0x0A, unsupported_parameter_value=0x0B, wrong_pin_code=0x0C, ) class PairingError(IntEnum): DEVICE_TIMEOUT = 0x01 DEVICE_NOT_SUPPORTED = 0x02 TOO_MANY_DEVICES = 0x03 SEQUENCE_TIMEOUT = 0x06 class BoltPairingError(IntEnum): DEVICE_TIMEOUT = 0x01 FAILED = 0x02 class Registers(IntEnum): """Known HID registers. Devices usually have a (small) sub-set of these. Some registers are only applicable to certain device kinds (e.g. smooth_scroll only applies to mice). """ # Generally applicable NOTIFICATIONS = 0x00 FIRMWARE = 0xF1 # only apply to receivers RECEIVER_CONNECTION = 0x02 RECEIVER_PAIRING = 0xB2 DEVICES_ACTIVITY = 0x2B3 RECEIVER_INFO = 0x2B5 BOLT_DEVICE_DISCOVERY = 0xC0 BOLT_PAIRING = 0x2C1 BOLT_UNIQUE_ID = 0x02FB # only apply to devices MOUSE_BUTTON_FLAGS = 0x01 KEYBOARD_HAND_DETECTION = 0x01 DEVICES_CONFIGURATION = 0x03 BATTERY_STATUS = 0x07 KEYBOARD_FN_SWAP = 0x09 BATTERY_CHARGE = 0x0D KEYBOARD_ILLUMINATION = 0x17 THREE_LEDS = 0x51 MOUSE_DPI = 0x63 # notifications PASSKEY_REQUEST_NOTIFICATION = 0x4D PASSKEY_PRESSED_NOTIFICATION = 0x4E DEVICE_DISCOVERY_NOTIFICATION = 0x4F DISCOVERY_STATUS_NOTIFICATION = 0x53 PAIRING_STATUS_NOTIFICATION = 0x54 # Subregisters for receiver_info register INFO_SUBREGISTERS = NamedInts( serial_number=0x01, # not found on many receivers fw_version=0x02, receiver_information=0x03, pairing_information=0x20, # 0x2N, by connected device extended_pairing_information=0x30, # 0x3N, by connected device device_name=0x40, # 0x4N, by connected device bolt_pairing_information=0x50, # 0x5N, by connected device bolt_device_name=0x60, # 0x6N01, by connected device, ) # Flags taken from https://drive.google.com/file/d/0BxbRzx7vEV7eNDBheWY0UHM5dEU/view?usp=sharing DEVICE_FEATURES = NamedInts( reserved1=0x010000, special_buttons=0x020000, enhanced_key_usage=0x040000, fast_fw_rev=0x080000, reserved2=0x100000, reserved3=0x200000, scroll_accel=0x400000, buttons_control_resolution=0x800000, inhibit_lock_key_sound=0x000001, reserved4=0x000002, mx_air_3d_engine=0x000004, host_control_leds=0x000008, reserved5=0x000010, reserved6=0x000020, reserved7=0x000040, reserved8=0x000080, )
6,154
Python
.py
166
33.198795
107
0.746774
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,467
descriptors.py
pwr-Solaar_Solaar/lib/logitech_receiver/descriptors.py
## Copyright (C) 2012-2013 Daniel Pavel ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """Devices (not receivers) known to Solaar. Solaar can handle many recent devices without having any entry here. An entry should only be added to fix problems, such as - the device's device ID or WPID falls outside the range that Solaar searches - the device uses a USB interface other than 2 - the name or codename should be different from what the device reports """ from .hidpp10_constants import DEVICE_KIND from .hidpp10_constants import Registers as Reg class _DeviceDescriptor: def __init__( self, name=None, kind=None, wpid=None, codename=None, protocol=None, registers=None, usbid=None, interface=None, btid=None, ): self.name = name self.kind = kind self.wpid = wpid self.codename = codename self.protocol = protocol self.registers = registers self.usbid = usbid self.interface = interface self.btid = btid self.settings = None DEVICES_WPID = {} DEVICES = {} def _D( name, codename=None, kind=None, wpid=None, protocol=None, registers=None, settings=None, usbid=None, interface=None, btid=None, ): if kind is None: kind = ( DEVICE_KIND.mouse if "Mouse" in name else DEVICE_KIND.keyboard if "Keyboard" in name else DEVICE_KIND.numpad if "Number Pad" in name else DEVICE_KIND.touchpad if "Touchpad" in name else DEVICE_KIND.trackball if "Trackball" in name else None ) assert kind is not None, f"descriptor for {name} does not have kind set" if protocol is not None: if wpid: for w in wpid if isinstance(wpid, tuple) else (wpid,): if protocol > 1.0: assert w[0:1] == "4", f"{name} has protocol {protocol:0.1f}, wpid {w}" else: if w[0:1] == "1": assert kind == DEVICE_KIND.mouse, f"{name} has protocol {protocol:0.1f}, wpid {w}" elif w[0:1] == "2": assert kind in ( DEVICE_KIND.keyboard, DEVICE_KIND.numpad, ), f"{name} has protocol {protocol:0.1f}, wpid {w}" device_descriptor = _DeviceDescriptor( name=name, kind=kind, wpid=wpid, codename=codename, protocol=protocol, registers=registers, usbid=usbid, interface=interface, btid=btid, ) if usbid: found = get_usbid(usbid) assert found is None, f"duplicate usbid in device descriptors: {found}" if btid: found = get_btid(btid) assert found is None, f"duplicate btid in device descriptors: {found}" assert codename not in DEVICES, f"duplicate codename in device descriptors: {DEVICES[codename]}" if codename: DEVICES[codename] = device_descriptor if wpid: for w in wpid if isinstance(wpid, tuple) else (wpid,): assert w not in DEVICES_WPID, f"duplicate wpid in device descriptors: {DEVICES_WPID[w]}" DEVICES_WPID[w] = device_descriptor def get_wpid(wpid): return DEVICES_WPID.get(wpid) def get_codename(codename): return DEVICES.get(codename) def get_usbid(usbid): if isinstance(usbid, str): usbid = int(usbid, 16) found = next((x for x in DEVICES.values() if x.usbid == usbid), None) return found def get_btid(btid): if isinstance(btid, str): btid = int(btid, 16) found = next((x for x in DEVICES.values() if x.btid == btid), None) return found # Some HID++1.0 registers and HID++2.0 features can be discovered at run-time, # so they are not specified here. # # State registers (battery, leds, some features, etc) are only used by # HID++ 1.0 devices, while HID++ 2.0 devices use features for the same # functionalities. # Well-known registers (in hex): # * 00 - notification flags (all devices) # 01 - mice: smooth scrolling # 07 - battery status # 09 - keyboards: FN swap (if it has the FN key) # 0D - battery charge # a device may have either the 07 or 0D register available; # no known device uses both # 51 - leds # 63 - mice: DPI # * F1 - firmware info # Some registers appear to be universally supported, no matter the HID++ version # (marked with *). The rest may or may not be supported, and their values may or # may not mean the same thing across different devices. # The 'codename' and 'kind' fields are usually guessed from the device name, # but in some cases (like the Logitech Cube) that heuristic fails and they have # to be specified. # # The 'protocol' and 'wpid' fields are optional (they can be discovered at # runtime), but specifying them here speeds up device discovery and reduces the # USB traffic Solaar has to do to fully identify peripherals. # # The 'registers' field indicates read-only registers, specifying a state. These # are valid (AFAIK) only to HID++ 1.0 devices. # The 'settings' field indicates a read/write register; based on them Solaar # generates, at runtime, the settings controls in the device panel. # Solaar now sets up this field in settings_templates.py to eliminate a imports loop. # HID++ 1.0 devices may only have register-based settings; HID++ 2.0 devices may only have # feature-based settings. # Devices are organized by kind # Within kind devices are sorted by wpid, then by usbid, then by btid, with missing values sorted later # Keyboards _D("Wireless Keyboard EX110", codename="EX110", protocol=1.0, wpid="0055", registers=(Reg.BATTERY_STATUS,)) _D("Wireless Keyboard S510", codename="S510", protocol=1.0, wpid="0056", registers=(Reg.BATTERY_STATUS,)) _D("Wireless Wave Keyboard K550", codename="K550", protocol=1.0, wpid="0060", registers=(Reg.BATTERY_STATUS,)) _D("Wireless Keyboard EX100", codename="EX100", protocol=1.0, wpid="0065", registers=(Reg.BATTERY_STATUS,)) _D("Wireless Keyboard MK300", codename="MK300", protocol=1.0, wpid="0068", registers=(Reg.BATTERY_STATUS,)) _D("Number Pad N545", codename="N545", protocol=1.0, wpid="2006", registers=(Reg.BATTERY_STATUS,)) _D("Wireless Compact Keyboard K340", codename="K340", protocol=1.0, wpid="2007", registers=(Reg.BATTERY_STATUS,)) _D("Wireless Keyboard MK700", codename="MK700", protocol=1.0, wpid="2008", registers=(Reg.BATTERY_STATUS,)) _D("Wireless Wave Keyboard K350", codename="K350", protocol=1.0, wpid="200A", registers=(Reg.BATTERY_STATUS,)) _D("Wireless Keyboard MK320", codename="MK320", protocol=1.0, wpid="200F", registers=(Reg.BATTERY_STATUS,)) _D( "Wireless Illuminated Keyboard K800", codename="K800", protocol=1.0, wpid="2010", registers=(Reg.BATTERY_STATUS, Reg.THREE_LEDS), ) _D("Wireless Keyboard K520", codename="K520", protocol=1.0, wpid="2011", registers=(Reg.BATTERY_STATUS,)) _D("Wireless Solar Keyboard K750", codename="K750", protocol=2.0, wpid="4002") _D("Wireless Keyboard K270 (unifying)", codename="K270", protocol=2.0, wpid="4003") _D("Wireless Keyboard K360", codename="K360", protocol=2.0, wpid="4004") _D("Wireless Keyboard K230", codename="K230", protocol=2.0, wpid="400D") _D("Wireless Touch Keyboard K400", codename="K400", protocol=2.0, wpid=("400E", "4024")) _D("Wireless Keyboard MK270", codename="MK270", protocol=2.0, wpid="4023") _D("Illuminated Living-Room Keyboard K830", codename="K830", protocol=2.0, wpid="4032") _D("Wireless Touch Keyboard K400 Plus", codename="K400 Plus", protocol=2.0, wpid="404D") _D("Wireless Multi-Device Keyboard K780", codename="K780", protocol=4.5, wpid="405B") _D("Wireless Keyboard K375s", codename="K375s", protocol=2.0, wpid="4061") _D("Craft Advanced Keyboard", codename="Craft", protocol=4.5, wpid="4066", btid=0xB350) _D("Wireless Illuminated Keyboard K800 new", codename="K800 new", protocol=4.5, wpid="406E") _D("Wireless Keyboard K470", codename="K470", protocol=4.5, wpid="4075") _D("MX Keys Keyboard", codename="MX Keys", protocol=4.5, wpid="408A", btid=0xB35B) _D( "G915 TKL LIGHTSPEED Wireless RGB Mechanical Gaming Keyboard", codename="G915 TKL", protocol=4.2, wpid="408E", usbid=0xC343, ) _D("Illuminated Keyboard", codename="Illuminated", protocol=1.0, usbid=0xC318, interface=1) _D("G213 Prodigy Gaming Keyboard", codename="G213", usbid=0xC336, interface=1) _D("G512 RGB Mechanical Gaming Keyboard", codename="G512", usbid=0xC33C, interface=1) _D("G815 Mechanical Keyboard", codename="G815", usbid=0xC33F, interface=1) _D("diNovo Edge Keyboard", codename="diNovo", protocol=1.0, wpid="C714") _D("K845 Mechanical Keyboard", codename="K845", usbid=0xC341, interface=3) # Mice _D("LX5 Cordless Mouse", codename="LX5", protocol=1.0, wpid="0036", registers=(Reg.BATTERY_STATUS,)) _D("LX7 Cordless Laser Mouse", codename="LX7", protocol=1.0, wpid="0039", registers=(Reg.BATTERY_STATUS,)) _D("Wireless Wave Mouse M550", codename="M550", protocol=1.0, wpid="003C", registers=(Reg.BATTERY_STATUS,)) _D("Wireless Mouse EX100", codename="EX100m", protocol=1.0, wpid="003F", registers=(Reg.BATTERY_STATUS,)) _D("Wireless Mouse M30", codename="M30", protocol=1.0, wpid="0085", registers=(Reg.BATTERY_STATUS,)) _D("MX610 Laser Cordless Mouse", codename="MX610", protocol=1.0, wpid="1001", registers=(Reg.BATTERY_STATUS,)) _D("G7 Cordless Laser Mouse", codename="G7", protocol=1.0, wpid="1002", registers=(Reg.BATTERY_STATUS,)) _D("V400 Laser Cordless Mouse", codename="V400", protocol=1.0, wpid="1003", registers=(Reg.BATTERY_STATUS,)) _D("MX610 Left-Handled Mouse", codename="MX610L", protocol=1.0, wpid="1004", registers=(Reg.BATTERY_STATUS,)) _D("V450 Laser Cordless Mouse", codename="V450", protocol=1.0, wpid="1005", registers=(Reg.BATTERY_STATUS,)) _D( "VX Revolution", codename="VX Revolution", kind=DEVICE_KIND.mouse, protocol=1.0, wpid=("1006", "100D", "0612"), registers=(Reg.BATTERY_CHARGE,), ) _D( "MX Air", codename="MX Air", protocol=1.0, kind=DEVICE_KIND.mouse, wpid=("1007", "100E"), registers=Reg.BATTERY_CHARGE, ) _D( "MX Revolution", codename="MX Revolution", protocol=1.0, kind=DEVICE_KIND.mouse, wpid=("1008", "100C"), registers=(Reg.BATTERY_CHARGE,), ) _D( "MX620 Laser Cordless Mouse", codename="MX620", protocol=1.0, wpid=("100A", "1016"), registers=(Reg.BATTERY_CHARGE,), ) _D( "VX Nano Cordless Laser Mouse", codename="VX Nano", protocol=1.0, wpid=("100B", "100F"), registers=(Reg.BATTERY_CHARGE,), ) _D( "V450 Nano Cordless Laser Mouse", codename="V450 Nano", protocol=1.0, wpid="1011", registers=(Reg.BATTERY_CHARGE,), ) _D( "V550 Nano Cordless Laser Mouse", codename="V550 Nano", protocol=1.0, wpid="1013", registers=(Reg.BATTERY_CHARGE,), ) _D( "MX 1100 Cordless Laser Mouse", codename="MX 1100", protocol=1.0, kind=DEVICE_KIND.mouse, wpid="1014", registers=(Reg.BATTERY_CHARGE,), ) _D("Anywhere Mouse MX", codename="Anywhere MX", protocol=1.0, wpid="1017", registers=(Reg.BATTERY_CHARGE,)) _D( "Performance Mouse MX", codename="Performance MX", protocol=1.0, wpid="101A", registers=(Reg.BATTERY_STATUS, Reg.THREE_LEDS), ) _D( "Marathon Mouse M705 (M-R0009)", codename="M705 (M-R0009)", protocol=1.0, wpid="101B", registers=(Reg.BATTERY_CHARGE,), ) _D( "Wireless Mouse M350", codename="M350", protocol=1.0, wpid="101C", registers=(Reg.BATTERY_CHARGE,), ) _D( "Wireless Mouse M505", codename="M505/B605", protocol=1.0, wpid="101D", registers=(Reg.BATTERY_CHARGE,), ) _D( "Wireless Mouse M305", codename="M305", protocol=1.0, wpid="101F", registers=(Reg.BATTERY_STATUS,), ) _D( "Wireless Mouse M215", codename="M215", protocol=1.0, wpid="1020", ) _D( "G700 Gaming Mouse", codename="G700", protocol=1.0, wpid="1023", usbid=0xC06B, interface=1, registers=( Reg.BATTERY_STATUS, Reg.THREE_LEDS, ), ) _D("Wireless Mouse M310", codename="M310", protocol=1.0, wpid="1024", registers=(Reg.BATTERY_STATUS,)) _D("Wireless Mouse M510", codename="M510", protocol=1.0, wpid="1025", registers=(Reg.BATTERY_STATUS,)) _D("Fujitsu Sonic Mouse", codename="Sonic", protocol=1.0, wpid="1029") _D( "G700s Gaming Mouse", codename="G700s", protocol=1.0, wpid="102A", usbid=0xC07C, interface=1, registers=( Reg.BATTERY_STATUS, Reg.THREE_LEDS, ), ) _D("Couch Mouse M515", codename="M515", protocol=2.0, wpid="4007") _D("Wireless Mouse M175", codename="M175", protocol=2.0, wpid="4008") _D("Wireless Mouse M325", codename="M325", protocol=2.0, wpid="400A") _D("Wireless Mouse M525", codename="M525", protocol=2.0, wpid="4013") _D("Wireless Mouse M345", codename="M345", protocol=2.0, wpid="4017") _D("Wireless Mouse M187", codename="M187", protocol=2.0, wpid="4019") _D("Touch Mouse M600", codename="M600", protocol=2.0, wpid="401A") _D("Wireless Mouse M150", codename="M150", protocol=2.0, wpid="4022") _D("Wireless Mouse M185", codename="M185", protocol=2.0, wpid="4038") _D("Wireless Mouse MX Master", codename="MX Master", protocol=4.5, wpid="4041", btid=0xB012) _D("Anywhere Mouse MX 2", codename="Anywhere MX 2", protocol=4.5, wpid="404A") _D("Wireless Mouse M510", codename="M510v2", protocol=2.0, wpid="4051") _D("Wireless Mouse M185 new", codename="M185n", protocol=4.5, wpid="4054") _D("Wireless Mouse M185/M235/M310", codename="M185/M235/M310", protocol=4.5, wpid="4055") _D("Wireless Mouse MX Master 2S", codename="MX Master 2S", protocol=4.5, wpid="4069", btid=0xB019) _D("Multi Device Silent Mouse M585/M590", codename="M585/M590", protocol=4.5, wpid="406B") _D( "Marathon Mouse M705 (M-R0073)", codename="M705 (M-R0073)", protocol=4.5, wpid="406D", ) _D("MX Vertical Wireless Mouse", codename="MX Vertical", protocol=4.5, wpid="407B", btid=0xB020, usbid=0xC08A) _D("Wireless Mouse Pebble M350", codename="Pebble", protocol=2.0, wpid="4080") _D("MX Master 3 Wireless Mouse", codename="MX Master 3", protocol=4.5, wpid="4082", btid=0xB023) _D("PRO X Wireless", kind="mouse", codename="PRO X", wpid="4093", usbid=0xC094) _D("G9 Laser Mouse", codename="G9", usbid=0xC048, interface=1, protocol=1.0) _D("G9x Laser Mouse", codename="G9x", usbid=0xC066, interface=1, protocol=1.0) _D("G502 Gaming Mouse", codename="G502", usbid=0xC07D, interface=1) _D("G402 Gaming Mouse", codename="G402", usbid=0xC07E, interface=1) _D("G900 Chaos Spectrum Gaming Mouse", codename="G900", usbid=0xC081) _D("G403 Gaming Mouse", codename="G403", usbid=0xC082) _D("G903 Lightspeed Gaming Mouse", codename="G903", usbid=0xC086) _D("G703 Lightspeed Gaming Mouse", codename="G703", usbid=0xC087) _D("GPro Gaming Mouse", codename="GPro", usbid=0xC088) _D("G502 SE Hero Gaming Mouse", codename="G502 Hero", usbid=0xC08B, interface=1) _D("G502 Lightspeed Gaming Mouse", codename="G502 Lightspeed", usbid=0xC08D) _D("MX518 Gaming Mouse", codename="MX518", usbid=0xC08E, interface=1) _D("G703 Hero Gaming Mouse", codename="G703 Hero", usbid=0xC090) _D("G903 Hero Gaming Mouse", codename="G903 Hero", usbid=0xC091) _D(None, kind=DEVICE_KIND.mouse, usbid=0xC092, interface=1) # two mice share this ID _D("M500S Mouse", codename="M500S", usbid=0xC093, interface=1) # _D('G600 Gaming Mouse', codename='G600 Gaming', usbid=0xc24a, interface=1) # not an HID++ device _D("G500s Gaming Mouse", codename="G500s Gaming", usbid=0xC24E, interface=1, protocol=1.0) _D("G502 Proteus Spectrum Optical Mouse", codename="G502 Proteus Spectrum", usbid=0xC332, interface=1) _D("Logitech PRO Gaming Keyboard", codename="PRO Gaming Keyboard", usbid=0xC339, interface=1) _D("Logitech MX Revolution Mouse M-RCL 124", codename="M-RCL 124", btid=0xB007, interface=1) # Trackballs _D("Wireless Trackball M570", codename="M570") # Touchpads _D("Wireless Touchpad", codename="Wireless Touch", protocol=2.0, wpid="4011") _D("Wireless Rechargeable Touchpad T650", codename="T650", protocol=2.0, wpid="4101") _D( "G Powerplay", codename="Powerplay", protocol=2.0, kind=DEVICE_KIND.touchpad, wpid="405F" ) # To override self-identification # Headset _D("G533 Gaming Headset", codename="G533 Headset", protocol=2.0, interface=3, kind=DEVICE_KIND.headset, usbid=0x0A66) _D("G535 Gaming Headset", codename="G535 Headset", protocol=2.0, interface=3, kind=DEVICE_KIND.headset, usbid=0x0AC4) _D("G935 Gaming Headset", codename="G935 Headset", protocol=2.0, interface=3, kind=DEVICE_KIND.headset, usbid=0x0A87) _D("G733 Gaming Headset", codename="G733 Headset", protocol=2.0, interface=3, kind=DEVICE_KIND.headset, usbid=0x0AB5) _D( "G733 Gaming Headset", codename="G733 Headset New", protocol=2.0, interface=3, kind=DEVICE_KIND.headset, usbid=0x0AFE, ) _D( "PRO X Wireless Gaming Headset", codename="PRO Headset", protocol=2.0, interface=3, kind=DEVICE_KIND.headset, usbid=0x0ABA, )
17,843
Python
.py
426
37.683099
117
0.684641
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,468
base.py
pwr-Solaar_Solaar/lib/logitech_receiver/base.py
## Copyright (C) 2012-2013 Daniel Pavel ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """Base low-level functions as API for upper layers.""" from __future__ import annotations import dataclasses import logging import platform import struct import threading import typing from contextlib import contextmanager from random import getrandbits from time import time from typing import Any from typing import Callable from . import base_usb from . import common from . import descriptors from . import exceptions from . import hidpp10_constants from . import hidpp20_constants from .common import LOGITECH_VENDOR_ID from .common import BusID if typing.TYPE_CHECKING: import gi from hidapi.common import DeviceInfo gi.require_version("Gdk", "3.0") from gi.repository import GLib # NOQA: E402 if platform.system() == "Linux": import hidapi.udev_impl as hidapi else: import hidapi.hidapi_impl as hidapi logger = logging.getLogger(__name__) class HIDAPI(typing.Protocol): def find_paired_node_wpid(self, receiver_path: str, index: int): ... def find_paired_node(self, receiver_path: str, index: int, timeout: int): ... def open(self, vendor_id, product_id, serial=None): ... def open_path(self, path): ... def enumerate(self, filter_func: Callable[[int, int, int, bool, bool], dict[str, typing.Any]]) -> DeviceInfo: ... def monitor_glib( self, glib: GLib, callback: Callable, filter_func: Callable[[int, int, int, bool, bool], dict[str, typing.Any]] ) -> None: ... def read(self, device_handle, bytes_count, timeout_ms): ... def write(self, device_handle: int, data: bytes) -> int: ... def close(self, device_handle) -> None: ... hidapi = typing.cast(HIDAPI, hidapi) SHORT_MESSAGE_SIZE = 7 _LONG_MESSAGE_SIZE = 20 _MEDIUM_MESSAGE_SIZE = 15 _MAX_READ_SIZE = 32 HIDPP_SHORT_MESSAGE_ID = 0x10 HIDPP_LONG_MESSAGE_ID = 0x11 DJ_MESSAGE_ID = 0x20 """Default timeout on read (in seconds).""" DEFAULT_TIMEOUT = 4 # the receiver itself should reply very fast, within 500ms _RECEIVER_REQUEST_TIMEOUT = 0.9 # devices may reply a lot slower, as the call has to go wireless to them and come back _DEVICE_REQUEST_TIMEOUT = DEFAULT_TIMEOUT # when pinging, be extra patient (no longer) _PING_TIMEOUT = DEFAULT_TIMEOUT @dataclasses.dataclass class HIDPPNotification: report_id: int devnumber: int sub_id: int address: int data: bytes def __str__(self): text_as_hex = common.strhex(self.data) return f"Notification({self.report_id:02x},{self.devnumber},{self.sub_id:02X},{self.address:02X},{text_as_hex})" def _usb_device(product_id: int, usb_interface: int) -> dict[str, Any]: return { "vendor_id": LOGITECH_VENDOR_ID, "product_id": product_id, "bus_id": BusID.USB, "usb_interface": usb_interface, "isDevice": True, } def _bluetooth_device(product_id: int) -> dict[str, Any]: return {"vendor_id": LOGITECH_VENDOR_ID, "product_id": product_id, "bus_id": BusID.BLUETOOTH, "isDevice": True} KNOWN_DEVICE_IDS = [] for _ignore, d in descriptors.DEVICES.items(): if d.usbid: usb_interface = d.interface if d.interface else 2 KNOWN_DEVICE_IDS.append(_usb_device(d.usbid, usb_interface)) if d.btid: KNOWN_DEVICE_IDS.append(_bluetooth_device(d.btid)) def _other_device_check(bus_id: int, vendor_id: int, product_id: int) -> dict[str, Any] | None: """Check whether product is a Logitech USB-connected or Bluetooth device based on bus, vendor, and product IDs This allows Solaar to support receiverless HID++ 2.0 devices that it knows nothing about""" if vendor_id != LOGITECH_VENDOR_ID: return device_info = None if bus_id == BusID.USB and (0xC07D <= product_id <= 0xC094 or 0xC32B <= product_id <= 0xC344): device_info = _usb_device(product_id, 2) elif bus_id == BusID.BLUETOOTH and (0xB012 <= product_id <= 0xB0FF or 0xB317 <= product_id <= 0xB3FF): device_info = _bluetooth_device(product_id) return device_info def product_information(usb_id: int) -> dict[str, Any]: """Returns hardcoded information from USB receiver.""" return base_usb.get_receiver_info(usb_id) def _match(record: dict[str, Any], bus_id: int, vendor_id: int, product_id: int): return ( (record.get("bus_id") is None or record.get("bus_id") == bus_id) and (record.get("vendor_id") is None or record.get("vendor_id") == vendor_id) and (record.get("product_id") is None or record.get("product_id") == product_id) ) def _filter_receivers( bus_id: int, vendor_id: int, product_id: int, _hidpp_short: bool = False, _hidpp_long: bool = False ) -> dict[str, Any]: """Check that this product is a Logitech receiver and return it. Filters based on bus_id, vendor_id and product_id. If so return the receiver record for further checking. """ try: record = base_usb.get_receiver_info(product_id) if _match(record, bus_id, vendor_id, product_id): return record except ValueError: pass if vendor_id == LOGITECH_VENDOR_ID and 0xC500 <= product_id <= 0xC5FF: # unknown receiver return {"vendor_id": vendor_id, "product_id": product_id, "bus_id": bus_id, "isDevice": False} return None def receivers(): """Enumerate all the receivers attached to the machine.""" yield from hidapi.enumerate(_filter_receivers) def _filter_products_of_interest( bus_id: int, vendor_id: int, product_id: int, hidpp_short: bool = False, hidpp_long: bool = False ) -> dict[str, Any] | None: """Check that this product is of interest and if so return the device record for further checking""" record = _filter_receivers(bus_id, vendor_id, product_id, hidpp_short, hidpp_long) if record: # known or unknown receiver return record for record in KNOWN_DEVICE_IDS: if _match(record, bus_id, vendor_id, product_id): return record if hidpp_short or hidpp_long: # unknown devices that use HID++ return {"vendor_id": vendor_id, "product_id": product_id, "bus_id": bus_id, "isDevice": True} elif hidpp_short is None and hidpp_long is None: # unknown devices in correct range of IDs return _other_device_check(bus_id, vendor_id, product_id) return None def receivers_and_devices(): """Enumerate all the receivers and devices directly attached to the machine.""" yield from hidapi.enumerate(_filter_products_of_interest) def notify_on_receivers_glib(glib: GLib, callback: Callable): """Watch for matching devices and notifies the callback on the GLib thread. Parameters ---------- glib GLib instance. """ return hidapi.monitor_glib(glib, callback, _filter_products_of_interest) def open_path(path): """Checks if the given Linux device path points to the right UR device. :param path: the Linux device path. The UR physical device may expose multiple linux devices with the same interface, so we have to check for the right one. At this moment the only way to distinguish betheen them is to do a test ping on an invalid (attached) device number (i.e., 0), expecting a 'ping failed' reply. :returns: an open receiver handle if this is the right Linux device, or ``None``. """ return hidapi.open_path(path) def open(): """Opens the first Logitech Unifying Receiver found attached to the machine. :returns: An open file handle for the found receiver, or ``None``. """ for rawdevice in receivers(): handle = open_path(rawdevice.path) if handle: return handle def close(handle): """Closes a HID device handle.""" if handle: try: if isinstance(handle, int): hidapi.close(handle) else: handle.close() return True except Exception: pass return False def write(handle, devnumber, data, long_message=False): """Writes some data to the receiver, addressed to a certain device. :param handle: an open UR handle. :param devnumber: attached device number. :param data: data to send, up to 5 bytes. The first two (required) bytes of data must be the SubId and address. :raises NoReceiver: if the receiver is no longer available, i.e. has been physically removed from the machine, or the kernel driver has been unloaded. The handle will be closed automatically. """ # the data is padded to either 5 or 18 bytes assert data is not None assert isinstance(data, bytes), (repr(data), type(data)) if long_message or len(data) > SHORT_MESSAGE_SIZE - 2 or data[:1] == b"\x82": wdata = struct.pack("!BB18s", HIDPP_LONG_MESSAGE_ID, devnumber, data) else: wdata = struct.pack("!BB5s", HIDPP_SHORT_MESSAGE_ID, devnumber, data) if logger.isEnabledFor(logging.DEBUG): logger.debug( "(%s) <= w[%02X %02X %s %s]", handle, ord(wdata[:1]), devnumber, common.strhex(wdata[2:4]), common.strhex(wdata[4:]), ) try: hidapi.write(int(handle), wdata) except Exception as reason: logger.error("write failed, assuming handle %r no longer available", handle) close(handle) raise exceptions.NoReceiver(reason=reason) from reason def read(handle, timeout=DEFAULT_TIMEOUT): """Read some data from the receiver. Usually called after a write (feature call), to get the reply. :param: handle open handle to the receiver :param: timeout how long to wait for a reply, in seconds :returns: a tuple of (devnumber, message data), or `None` :raises NoReceiver: if the receiver is no longer available, i.e. has been physically removed from the machine, or the kernel driver has been unloaded. The handle will be closed automatically. """ reply = _read(handle, timeout) if reply: return reply def _is_relevant_message(data: bytes) -> bool: """Checks if given id is a HID++ or DJ message. Applies sanity checks on message report ID and message size. """ assert isinstance(data, bytes), (repr(data), type(data)) # mapping from report_id to message length report_lengths = { HIDPP_SHORT_MESSAGE_ID: SHORT_MESSAGE_SIZE, HIDPP_LONG_MESSAGE_ID: _LONG_MESSAGE_SIZE, DJ_MESSAGE_ID: _MEDIUM_MESSAGE_SIZE, 0x21: _MAX_READ_SIZE, } report_id = ord(data[:1]) if report_id in report_lengths: if report_lengths.get(report_id) == len(data): return True else: logger.warning(f"unexpected message size: report_id {report_id:02X} message {common.strhex(data)}") return False def _read(handle, timeout): """Read an incoming packet from the receiver. :returns: a tuple of (report_id, devnumber, data), or `None`. :raises NoReceiver: if the receiver is no longer available, i.e. has been physically removed from the machine, or the kernel driver has been unloaded. The handle will be closed automatically. """ try: # convert timeout to milliseconds, the hidapi expects it timeout = int(timeout * 1000) data = hidapi.read(int(handle), _MAX_READ_SIZE, timeout) except Exception as reason: logger.warning("read failed, assuming handle %r no longer available", handle) close(handle) raise exceptions.NoReceiver(reason=reason) from reason if data and _is_relevant_message(data): # ignore messages that fail check report_id = ord(data[:1]) devnumber = ord(data[1:2]) if logger.isEnabledFor(logging.DEBUG) and ( report_id != DJ_MESSAGE_ID or ord(data[2:3]) > 0x10 ): # ignore DJ input messages logger.debug( "(%s) => r[%02X %02X %s %s]", handle, report_id, devnumber, common.strhex(data[2:4]), common.strhex(data[4:]), ) return report_id, devnumber, data[2:] def _skip_incoming(handle, ihandle, notifications_hook): """Read anything already in the input buffer. Used by request() and ping() before their write. """ while True: try: # read whatever is already in the buffer, if any data = hidapi.read(ihandle, _MAX_READ_SIZE, 0) except Exception as reason: logger.error("read failed, assuming receiver %s no longer available", handle) close(handle) raise exceptions.NoReceiver(reason=reason) from reason if data: if _is_relevant_message(data): # only process messages that pass check # report_id = ord(data[:1]) if notifications_hook: n = make_notification(ord(data[:1]), ord(data[1:2]), data[2:]) if n: notifications_hook(n) else: # nothing in the input buffer, we're done return def make_notification(report_id: int, devnumber: int, data: bytes) -> HIDPPNotification | None: """Guess if this is a notification (and not just a request reply), and return a Notification if it is.""" sub_id = ord(data[:1]) if sub_id & 0x80 == 0x80: # this is either a HID++1.0 register r/w, or an error reply return None # DJ input records are not notifications if report_id == DJ_MESSAGE_ID and (sub_id < 0x10): return None address = ord(data[1:2]) if sub_id == 0x00 and (address & 0x0F == 0x00): # this is a no-op notification - don't do anything with it return None if ( # standard HID++ 1.0 notification, SubId may be 0x40 - 0x7F (sub_id >= 0x40) # noqa: E131 or # custom HID++1.0 battery events, where SubId is 0x07/0x0D (sub_id in (0x07, 0x0D) and len(data) == 5 and data[4:5] == b"\x00") or # custom HID++1.0 illumination event, where SubId is 0x17 (sub_id == 0x17 and len(data) == 5) or # HID++ 2.0 feature notifications have the SoftwareID 0 (address & 0x0F == 0x00) ): # noqa: E129 return HIDPPNotification(report_id, devnumber, sub_id, address, data[2:]) return None request_lock = threading.Lock() # serialize all requests handles_lock = {} def handle_lock(handle): with request_lock: if handles_lock.get(handle) is None: if logger.isEnabledFor(logging.INFO): logger.info("New lock %s", repr(handle)) handles_lock[handle] = threading.Lock() # Serialize requests on the handle return handles_lock[handle] # context manager for locks with a timeout @contextmanager def acquire_timeout(lock, handle, timeout): result = lock.acquire(timeout=timeout) try: if not result: logger.error("lock on handle %d not acquired, probably due to timeout", int(handle)) yield result finally: if result: lock.release() def _get_next_sw_id() -> int: """Returns 'random' software ID to separate replies from different devices. Cycle the HID++ 2.0 software ID from 0x2 to 0xF to separate results and notifications. """ if not hasattr(_get_next_sw_id, "software_id"): _get_next_sw_id.software_id = 0xF if _get_next_sw_id.software_id < 0xF: _get_next_sw_id.software_id += 1 else: _get_next_sw_id.software_id = 2 return _get_next_sw_id.software_id def find_paired_node(receiver_path: str, index: int, timeout: int): """Find the node of a device paired with a receiver.""" return hidapi.find_paired_node(receiver_path, index, timeout) def find_paired_node_wpid(receiver_path: str, index: int): """Find the node of a device paired with a receiver. Get wpid from udev. """ return hidapi.find_paired_node_wpid(receiver_path, index) # a very few requests (e.g., host switching) do not expect a reply, but use no_reply=True with extreme caution def request( handle, devnumber, request_id: int, *params, no_reply: bool = False, return_error: bool = False, long_message: bool = False, protocol: float = 1.0, ): """Makes a feature call to a device and waits for a matching reply. :param handle: an open UR handle. :param devnumber: attached device number. :param request_id: a 16-bit integer. :param params: parameters for the feature call, 3 to 16 bytes. :returns: the reply data, or ``None`` if some error occurred. or no reply expected """ with acquire_timeout(handle_lock(handle), handle, 10.0): assert isinstance(request_id, int) if (devnumber != 0xFF or protocol >= 2.0) and request_id < 0x8000: # Always set the most significant bit (8) in SoftwareId, # to make notifications easier to distinguish from request replies. # This only applies to peripheral requests, ofc. sw_id = _get_next_sw_id() request_id = (request_id & 0xFFF0) | sw_id # was 0x08 | getrandbits(3) timeout = _RECEIVER_REQUEST_TIMEOUT if devnumber == 0xFF else _DEVICE_REQUEST_TIMEOUT # be extra patient on long register read if request_id & 0xFF00 == 0x8300: timeout *= 2 if params: params = b"".join(struct.pack("B", p) if isinstance(p, int) else p for p in params) else: params = b"" request_data = struct.pack("!H", request_id) + params ihandle = int(handle) notifications_hook = getattr(handle, "notifications_hook", None) try: _skip_incoming(handle, ihandle, notifications_hook) except exceptions.NoReceiver: logger.warning("device or receiver disconnected") return None write(ihandle, devnumber, request_data, long_message) if no_reply: return None # we consider timeout from this point request_started = time() delta = 0 while delta < timeout: reply = _read(handle, timeout) if reply: report_id, reply_devnumber, reply_data = reply if reply_devnumber == devnumber or reply_devnumber == devnumber ^ 0xFF: # BT device returning 0x00 if ( report_id == HIDPP_SHORT_MESSAGE_ID and reply_data[:1] == b"\x8f" and reply_data[1:3] == request_data[:2] ): error = ord(reply_data[3:4]) if logger.isEnabledFor(logging.DEBUG): logger.debug( "(%s) device 0x%02X error on request {%04X}: %d = %s", handle, devnumber, request_id, error, hidpp10_constants.ERROR[error], ) return hidpp10_constants.ERROR[error] if return_error else None if reply_data[:1] == b"\xff" and reply_data[1:3] == request_data[:2]: # a HID++ 2.0 feature call returned with an error error = ord(reply_data[3:4]) logger.error( "(%s) device %d error on feature request {%04X}: %d = %s", handle, devnumber, request_id, error, hidpp20_constants.ERROR[error], ) raise exceptions.FeatureCallError( number=devnumber, request=request_id, error=error, params=params, ) if reply_data[:2] == request_data[:2]: if devnumber == 0xFF: if request_id == 0x83B5 or request_id == 0x81F1: # these replies have to match the first parameter as well if reply_data[2:3] == params[:1]: return reply_data[2:] else: # hm, not matching my request, and certainly not a notification continue else: return reply_data[2:] else: return reply_data[2:] else: # a reply was received, but did not match our request in any way # reset the timeout starting point request_started = time() if notifications_hook: n = make_notification(report_id, reply_devnumber, reply_data) if n: notifications_hook(n) delta = time() - request_started logger.warning( "timeout (%0.2f/%0.2f) on device %d request {%04X} params [%s]", delta, timeout, devnumber, request_id, common.strhex(params), ) # raise DeviceUnreachable(number=devnumber, request=request_id) def ping(handle, devnumber, long_message: bool = False): """Check if a device is connected to the receiver. :returns: The HID protocol supported by the device, as a floating point number, if the device is active. """ if logger.isEnabledFor(logging.DEBUG): logger.debug("(%s) pinging device %d", handle, devnumber) with acquire_timeout(handle_lock(handle), handle, 10.0): notifications_hook = getattr(handle, "notifications_hook", None) try: _skip_incoming(handle, int(handle), notifications_hook) except exceptions.NoReceiver: logger.warning("device or receiver disconnected") return # randomize the mark byte to be able to identify the ping reply sw_id = _get_next_sw_id() request_id = 0x0010 | sw_id # was 0x0018 | getrandbits(3) request_data = struct.pack("!HBBB", request_id, 0, 0, getrandbits(8)) write(int(handle), devnumber, request_data, long_message) request_started = time() # we consider timeout from this point delta = 0 while delta < _PING_TIMEOUT: reply = _read(handle, _PING_TIMEOUT) if reply: report_id, reply_devnumber, reply_data = reply if reply_devnumber == devnumber or reply_devnumber == devnumber ^ 0xFF: # BT device returning 0x00 if reply_data[:2] == request_data[:2] and reply_data[4:5] == request_data[-1:]: # HID++ 2.0+ device, currently connected return ord(reply_data[2:3]) + ord(reply_data[3:4]) / 10.0 if ( report_id == HIDPP_SHORT_MESSAGE_ID and reply_data[:1] == b"\x8f" and reply_data[1:3] == request_data[:2] ): # error response error = ord(reply_data[3:4]) if error == hidpp10_constants.ERROR.invalid_SubID__command: # a valid reply from a HID++ 1.0 device return 1.0 if ( error == hidpp10_constants.ERROR.resource_error or error == hidpp10_constants.ERROR.connection_request_failed ): return # device unreachable if error == hidpp10_constants.ERROR.unknown_device: # no paired device with that number logger.error("(%s) device %d error on ping request: unknown device", handle, devnumber) raise exceptions.NoSuchDevice(number=devnumber, request=request_id) if notifications_hook: n = make_notification(report_id, reply_devnumber, reply_data) if n: notifications_hook(n) delta = time() - request_started logger.warning("(%s) timeout (%0.2f/%0.2f) on device %d ping", handle, delta, _PING_TIMEOUT, devnumber)
25,415
Python
.py
559
35.744186
120
0.611401
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,469
settings_templates.py
pwr-Solaar_Solaar/lib/logitech_receiver/settings_templates.py
## Copyright (C) 2012-2013 Daniel Pavel ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from __future__ import annotations import enum import logging import socket import struct import traceback from time import time from typing import Any from typing import Callable from solaar.i18n import _ from . import base from . import common from . import descriptors from . import desktop_notifications from . import diversion from . import hidpp10_constants from . import hidpp20 from . import hidpp20_constants from . import settings from . import special_keys from .hidpp10_constants import Registers logger = logging.getLogger(__name__) _hidpp20 = hidpp20.Hidpp20() _DK = hidpp10_constants.DEVICE_KIND _F = hidpp20_constants.SupportedFeature _GG = hidpp20_constants.GESTURE _GP = hidpp20_constants.PARAM class State(enum.Enum): IDLE = "idle" PRESSED = "pressed" MOVED = "moved" # Setting classes are used to control the settings that the Solaar GUI shows and manipulates. # Each setting class has to several class variables: # name, which is used as a key when storing information about the setting, # setting classes can have the same name, as long as devices only have one setting with the same name; # label, which is shown in the Solaar main window; # description, which is shown when the mouse hovers over the setting in the main window; # either register or feature, the register or feature that the setting uses; # rw_class, the class of the reader/writer (if it is not the standard one), # rw_options, a dictionary of options for the reader/writer. # validator_class, the class of the validator (default settings.BooleanValidator) # validator_options, a dictionary of options for the validator # persist (inherited True), which is whether to store the value and apply it when setting up the device. # # The different setting classes imported from settings.py are for different numbers and kinds of arguments. # Setting is for settings with a single value (boolean, number in a range, and symbolic choice). # Settings is for settings that are maps from keys to values # and permit reading or writing the entire map or just one key/value pair. # The BitFieldSetting class is for settings that have multiple boolean values packed into a bit field. # BitFieldWithOffsetAndMaskSetting is similar. # The RangeFieldSetting class is for settings that have multiple ranges packed into a byte string. # LongSettings is for settings that have an even more complex structure. # # When settings are created a reader/writer and a validator are created. # If the setting class has a value for rw_class then an instance of that class is created. # Otherwise if the setting has a register then an instance of RegisterRW is created. # and if the setting has a feature then an instance of FeatureRW is created. # The instance is created with the register or feature as the first argument and rw_options as keyword arguments. # RegisterRW doesn't use any options. # FeatureRW options include # read_fnid - the feature function (times 16) to read the value (default 0x00), # write_fnid - the feature function (times 16) to write the value (default 0x10), # prefix - a prefix to add to the data being written and the read request (default b''), used for features # that provide and set multiple settings (e.g., to read and write function key inversion for current host) # no_reply - whether to wait for a reply (default false) (USE WITH EXTREME CAUTION). # # There are three simple validator classes - BooleanV, RangeValidator, and ChoicesValidator # BooleanV is for boolean values and is the default. It takes # true_value is the raw value for true (default 0x01), this can be an integer or a byte string, # false_value is the raw value for false (default 0x00), this can be an integer or a byte string, # mask is used to keep only some bits from a sequence of bits, this can be an integer or a byte string, # read_skip_byte_count is the number of bytes to ignore at the beginning of the read value (default 0), # write_prefix_bytes is a byte string to write before the value (default empty). # RangeValidator is for an integer in a range. It takes # byte_count is number of bytes that the value is stored in (defaults to size of max_value). # RangeValidator uses min_value and max_value from the setting class as minimum and maximum. # ChoicesValidator is for symbolic choices. It takes one positional and three keyword arguments: # choices is a list of named integers that are the valid choices, # byte_count is the number of bytes for the integer (default size of largest choice integer), # read_skip_byte_count is as for BooleanV, # write_prefix_bytes is as for BooleanV. # Settings that use ChoicesValidator should have a choices_universe class variable of the potential choices, # or None for no limitation and optionally a choices_extra class variable with an extra choice. # The choices_extra is so that there is no need to specially extend a large existing NamedInts. # ChoicesMapValidator validator is for map settings that map onto symbolic choices. It takes # choices_map is a map from keys to possible values # byte_count is as for ChoicesValidator, # read_skip_byte_count is as for ChoicesValidator, # write_prefix_bytes is as for ChoicesValidator, # key_byte_count is the number of bytes for the key integer (default size of largest key), # extra_default is an extra raw value that is used as a default value (default None). # Settings that use ChoicesValidator should have keys_universe and choices_universe class variable of # the potential keys and potential choices or None for no limitation. # BitFieldValidator validator is for bit field settings. It takes one positional and one keyword argument # the positional argument is the number of bits in the bit field # byte_count is the size of the bit field (default size of the bit field) # # A few settings work very differently. They divert a key, which is then used to start and stop some special action. # These settings have reader/writer classes that perform special processing instead of sending commands to the device. class FnSwapVirtual(settings.Setting): # virtual setting to hold fn swap strings name = "fn-swap" label = _("Swap Fx function") description = ( _( "When set, the F1..F12 keys will activate their special function,\n" "and you must hold the FN key to activate their standard function." ) + "\n\n" + _( "When unset, the F1..F12 keys will activate their standard function,\n" "and you must hold the FN key to activate their special function." ) ) class RegisterHandDetection(settings.Setting): name = "hand-detection" label = _("Hand Detection") description = _("Turn on illumination when the hands hover over the keyboard.") register = Registers.KEYBOARD_HAND_DETECTION validator_options = {"true_value": b"\x00\x00\x00", "false_value": b"\x00\x00\x30", "mask": b"\x00\x00\xff"} class RegisterSmoothScroll(settings.Setting): name = "smooth-scroll" label = _("Scroll Wheel Smooth Scrolling") description = _("High-sensitivity mode for vertical scroll with the wheel.") register = Registers.MOUSE_BUTTON_FLAGS validator_options = {"true_value": 0x40, "mask": 0x40} class RegisterSideScroll(settings.Setting): name = "side-scroll" label = _("Side Scrolling") description = _( "When disabled, pushing the wheel sideways sends custom button events\n" "instead of the standard side-scrolling events." ) register = Registers.MOUSE_BUTTON_FLAGS validator_options = {"true_value": 0x02, "mask": 0x02} # different devices have different sets of permissible dpis, so this should be subclassed class RegisterDpi(settings.Setting): name = "dpi-old" label = _("Sensitivity (DPI - older mice)") description = _("Mouse movement sensitivity") register = Registers.MOUSE_DPI choices_universe = common.NamedInts.range(0x81, 0x8F, lambda x: str((x - 0x80) * 100)) validator_class = settings.ChoicesValidator validator_options = {"choices": choices_universe} class RegisterFnSwap(FnSwapVirtual): register = Registers.KEYBOARD_FN_SWAP validator_options = {"true_value": b"\x00\x01", "mask": b"\x00\x01"} class _PerformanceMXDpi(RegisterDpi): choices_universe = common.NamedInts.range(0x81, 0x8F, lambda x: str((x - 0x80) * 100)) validator_options = {"choices": choices_universe} # set up register settings for devices - this is done here to break up an import loop descriptors.get_wpid("0060").settings = [RegisterFnSwap] descriptors.get_wpid("2008").settings = [RegisterFnSwap] descriptors.get_wpid("2010").settings = [RegisterFnSwap, RegisterHandDetection] descriptors.get_wpid("2011").settings = [RegisterFnSwap] descriptors.get_usbid(0xC318).settings = [RegisterFnSwap] descriptors.get_wpid("C714").settings = [RegisterFnSwap] descriptors.get_wpid("100B").settings = [RegisterSmoothScroll, RegisterSideScroll] descriptors.get_wpid("100F").settings = [RegisterSmoothScroll, RegisterSideScroll] descriptors.get_wpid("1013").settings = [RegisterSmoothScroll, RegisterSideScroll] descriptors.get_wpid("1014").settings = [RegisterSmoothScroll, RegisterSideScroll] descriptors.get_wpid("1017").settings = [RegisterSmoothScroll, RegisterSideScroll] descriptors.get_wpid("1023").settings = [RegisterSmoothScroll, RegisterSideScroll] descriptors.get_wpid("4004").settings = [_PerformanceMXDpi, RegisterSmoothScroll, RegisterSideScroll] descriptors.get_wpid("101A").settings = [_PerformanceMXDpi, RegisterSmoothScroll, RegisterSideScroll] descriptors.get_wpid("101B").settings = [RegisterSmoothScroll, RegisterSideScroll] descriptors.get_wpid("101D").settings = [RegisterSmoothScroll, RegisterSideScroll] descriptors.get_wpid("101F").settings = [RegisterSideScroll] descriptors.get_usbid(0xC06B).settings = [RegisterSmoothScroll, RegisterSideScroll] descriptors.get_wpid("1025").settings = [RegisterSideScroll] descriptors.get_wpid("102A").settings = [RegisterSmoothScroll, RegisterSideScroll] descriptors.get_usbid(0xC048).settings = [_PerformanceMXDpi, RegisterSmoothScroll, RegisterSideScroll] descriptors.get_usbid(0xC066).settings = [_PerformanceMXDpi, RegisterSmoothScroll, RegisterSideScroll] # ignore the capabilities part of the feature - all devices should be able to swap Fn state # can't just use the first byte = 0xFF (for current host) because of a bug in the firmware of the MX Keys S class K375sFnSwap(FnSwapVirtual): feature = _F.K375S_FN_INVERSION validator_options = {"true_value": b"\x01", "false_value": b"\x00", "read_skip_byte_count": 1} class rw_class(settings.FeatureRW): def find_current_host(self, device): if not self.prefix: response = device.feature_request(_F.HOSTS_INFO, 0x00) self.prefix = response[3:4] if response else b"\xff" def read(self, device, data_bytes=b""): self.find_current_host(device) return super().read(device, data_bytes) def write(self, device, data_bytes): self.find_current_host(device) return super().write(device, data_bytes) class FnSwap(FnSwapVirtual): feature = _F.FN_INVERSION class NewFnSwap(FnSwapVirtual): feature = _F.NEW_FN_INVERSION class Backlight(settings.Setting): name = "backlight-qualitative" label = _("Backlight Timed") description = _("Set illumination time for keyboard.") feature = _F.BACKLIGHT choices_universe = common.NamedInts(Off=0, Varying=2, VeryShort=5, Short=10, Medium=20, Long=60, VeryLong=180) validator_class = settings.ChoicesValidator validator_options = {"choices": choices_universe} # MX Keys S requires some extra values, as in 11 02 0c1a 000dff000b000b003c00000000000000 # on/off options (from current) effect (FF-no change) level (from current) durations[6] (from current) class Backlight2(settings.Setting): name = "backlight" label = _("Backlight") description = _("Illumination level on keyboard. Changes made are only applied in Manual mode.") feature = _F.BACKLIGHT2 choices_universe = common.NamedInts(Disabled=0xFF, Enabled=0x00, Automatic=0x01, Manual=0x02) min_version = 0 class rw_class: def __init__(self, feature): self.feature = feature self.kind = settings.FeatureRW.kind def read(self, device): backlight = device.backlight if not backlight.enabled: return b"\xff" else: return common.int2bytes(backlight.mode, 1) def write(self, device, data_bytes): backlight = device.backlight backlight.enabled = data_bytes[0] != 0xFF if data_bytes[0] != 0xFF: backlight.mode = data_bytes[0] backlight.write() return True class validator_class(settings.ChoicesValidator): @classmethod def build(cls, setting_class, device): backlight = device.backlight choices = common.NamedInts() choices[0xFF] = _("Disabled") if backlight.auto_supported: choices[0x1] = _("Automatic") if backlight.perm_supported: choices[0x3] = _("Manual") if not (backlight.auto_supported or backlight.temp_supported or backlight.perm_supported): choices[0x0] = _("Enabled") return cls(choices=choices, byte_count=1) class Backlight2Level(settings.Setting): name = "backlight_level" label = _("Backlight Level") description = _("Illumination level on keyboard when in Manual mode.") feature = _F.BACKLIGHT2 min_version = 3 class rw_class: def __init__(self, feature): self.feature = feature self.kind = settings.FeatureRW.kind def read(self, device): backlight = device.backlight return common.int2bytes(backlight.level, 1) def write(self, device, data_bytes): if device.backlight.level != common.bytes2int(data_bytes): device.backlight.level = common.bytes2int(data_bytes) device.backlight.write() return True class validator_class(settings.RangeValidator): @classmethod def build(cls, setting_class, device): reply = device.feature_request(_F.BACKLIGHT2, 0x20) assert reply, "Oops, backlight range cannot be retrieved!" if reply[0] > 1: return cls(min_value=0, max_value=reply[0] - 1, byte_count=1) class Backlight2Duration(settings.Setting): feature = _F.BACKLIGHT2 min_version = 3 validator_class = settings.RangeValidator min_value = 1 max_value = 600 # 10 minutes - actual maximum is 2 hours validator_options = {"byte_count": 2} class rw_class: def __init__(self, feature, field): self.feature = feature self.kind = settings.FeatureRW.kind self.field = field def read(self, device): backlight = device.backlight return common.int2bytes(getattr(backlight, self.field) * 5, 2) # use seconds instead of 5-second units def write(self, device, data_bytes): backlight = device.backlight new_duration = (int.from_bytes(data_bytes, byteorder="big") + 4) // 5 # use ceiling in 5-second units if new_duration != getattr(backlight, self.field): setattr(backlight, self.field, new_duration) backlight.write() return True class Backlight2DurationHandsOut(Backlight2Duration): name = "backlight_duration_hands_out" label = _("Backlight Delay Hands Out") description = _("Delay in seconds until backlight fades out with hands away from keyboard.") feature = _F.BACKLIGHT2 validator_class = settings.RangeValidator rw_options = {"field": "dho"} class Backlight2DurationHandsIn(Backlight2Duration): name = "backlight_duration_hands_in" label = _("Backlight Delay Hands In") description = _("Delay in seconds until backlight fades out with hands near keyboard.") feature = _F.BACKLIGHT2 validator_class = settings.RangeValidator rw_options = {"field": "dhi"} class Backlight2DurationPowered(Backlight2Duration): name = "backlight_duration_powered" label = _("Backlight Delay Powered") description = _("Delay in seconds until backlight fades out with external power.") feature = _F.BACKLIGHT2 validator_class = settings.RangeValidator rw_options = {"field": "dpow"} class Backlight3(settings.Setting): name = "backlight-timed" label = _("Backlight (Seconds)") description = _("Set illumination time for keyboard.") feature = _F.BACKLIGHT3 rw_options = {"read_fnid": 0x10, "write_fnid": 0x20, "suffix": b"\x09"} validator_class = settings.RangeValidator min_value = 0 max_value = 1000 validator_options = {"byte_count": 2} class HiResScroll(settings.Setting): name = "hi-res-scroll" label = _("Scroll Wheel High Resolution") description = ( _("High-sensitivity mode for vertical scroll with the wheel.") + "\n" + _("Set to ignore if scrolling is abnormally fast or slow") ) feature = _F.HI_RES_SCROLLING class LowresMode(settings.Setting): name = "lowres-scroll-mode" label = _("Scroll Wheel Diversion") description = _( "Make scroll wheel send LOWRES_WHEEL HID++ notifications (which trigger Solaar rules but are otherwise ignored)." ) feature = _F.LOWRES_WHEEL class HiresSmoothInvert(settings.Setting): name = "hires-smooth-invert" label = _("Scroll Wheel Direction") description = _("Invert direction for vertical scroll with wheel.") feature = _F.HIRES_WHEEL rw_options = {"read_fnid": 0x10, "write_fnid": 0x20} validator_options = {"true_value": 0x04, "mask": 0x04} class HiresSmoothResolution(settings.Setting): name = "hires-smooth-resolution" label = _("Scroll Wheel Resolution") description = ( _("High-sensitivity mode for vertical scroll with the wheel.") + "\n" + _("Set to ignore if scrolling is abnormally fast or slow") ) feature = _F.HIRES_WHEEL rw_options = {"read_fnid": 0x10, "write_fnid": 0x20} validator_options = {"true_value": 0x02, "mask": 0x02} class HiresMode(settings.Setting): name = "hires-scroll-mode" label = _("Scroll Wheel Diversion") description = _( "Make scroll wheel send HIRES_WHEEL HID++ notifications (which trigger Solaar rules but are otherwise ignored)." ) feature = _F.HIRES_WHEEL rw_options = {"read_fnid": 0x10, "write_fnid": 0x20} validator_options = {"true_value": 0x01, "mask": 0x01} class PointerSpeed(settings.Setting): name = "pointer_speed" label = _("Sensitivity (Pointer Speed)") description = _("Speed multiplier for mouse (256 is normal multiplier).") feature = _F.POINTER_SPEED validator_class = settings.RangeValidator min_value = 0x002E max_value = 0x01FF validator_options = {"byte_count": 2} class ThumbMode(settings.Setting): name = "thumb-scroll-mode" label = _("Thumb Wheel Diversion") description = _( "Make thumb wheel send THUMB_WHEEL HID++ notifications (which trigger Solaar rules but are otherwise ignored)." ) feature = _F.THUMB_WHEEL rw_options = {"read_fnid": 0x10, "write_fnid": 0x20} validator_options = {"true_value": b"\x01\x00", "false_value": b"\x00\x00", "mask": b"\x01\x00"} class ThumbInvert(settings.Setting): name = "thumb-scroll-invert" label = _("Thumb Wheel Direction") description = _("Invert thumb wheel scroll direction.") feature = _F.THUMB_WHEEL rw_options = {"read_fnid": 0x10, "write_fnid": 0x20} validator_options = {"true_value": b"\x00\x01", "false_value": b"\x00\x00", "mask": b"\x00\x01"} # change UI to show result of onboard profile change def profile_change(device, profile_sector): if device.setting_callback: device.setting_callback(device, OnboardProfiles, [profile_sector]) for profile in device.profiles.profiles.values() if device.profiles else []: if profile.sector == profile_sector: resolution_index = profile.resolution_default_index device.setting_callback(device, AdjustableDpi, [profile.resolutions[resolution_index]]) device.setting_callback(device, ReportRate, [profile.report_rate]) break class OnboardProfiles(settings.Setting): name = "onboard_profiles" label = _("Onboard Profiles") description = _("Enable an onboard profile, which controls report rate, sensitivity, and button actions") feature = _F.ONBOARD_PROFILES choices_universe = common.NamedInts(Disabled=0) for i in range(1, 16): choices_universe[i] = f"Profile {i}" choices_universe[i + 0x100] = f"Read-Only Profile {i}" validator_class = settings.ChoicesValidator class rw_class: def __init__(self, feature): self.feature = feature self.kind = settings.FeatureRW.kind def read(self, device): enabled = device.feature_request(_F.ONBOARD_PROFILES, 0x20)[0] if enabled == 0x01: active = device.feature_request(_F.ONBOARD_PROFILES, 0x40) return active[:2] else: return b"\x00\x00" def write(self, device, data_bytes): if data_bytes == b"\x00\x00": result = device.feature_request(_F.ONBOARD_PROFILES, 0x10, b"\x02") else: device.feature_request(_F.ONBOARD_PROFILES, 0x10, b"\x01") result = device.feature_request(_F.ONBOARD_PROFILES, 0x30, data_bytes) profile_change(device, common.bytes2int(data_bytes)) return result class validator_class(settings.ChoicesValidator): @classmethod def build(cls, setting_class, device): headers = hidpp20.OnboardProfiles.get_profile_headers(device) profiles_list = [setting_class.choices_universe[0]] if headers: for sector, enabled in headers: if enabled and setting_class.choices_universe[sector]: profiles_list.append(setting_class.choices_universe[sector]) return cls(choices=common.NamedInts.list(profiles_list), byte_count=2) if len(profiles_list) > 1 else None class ReportRate(settings.Setting): name = "report_rate" label = _("Report Rate") description = ( _("Frequency of device movement reports") + "\n" + _("May need Onboard Profiles set to Disable to be effective.") ) feature = _F.REPORT_RATE rw_options = {"read_fnid": 0x10, "write_fnid": 0x20} choices_universe = common.NamedInts() choices_universe[1] = "1ms" choices_universe[2] = "2ms" choices_universe[3] = "3ms" choices_universe[4] = "4ms" choices_universe[5] = "5ms" choices_universe[6] = "6ms" choices_universe[7] = "7ms" choices_universe[8] = "8ms" class validator_class(settings.ChoicesValidator): @classmethod def build(cls, setting_class, device): # if device.wpid == '408E': # return None # host mode borks the function keys on the G915 TKL keyboard reply = device.feature_request(_F.REPORT_RATE, 0x00) assert reply, "Oops, report rate choices cannot be retrieved!" rate_list = [] rate_flags = common.bytes2int(reply[0:1]) for i in range(0, 8): if (rate_flags >> i) & 0x01: rate_list.append(setting_class.choices_universe[i + 1]) return cls(choices=common.NamedInts.list(rate_list), byte_count=1) if rate_list else None class ExtendedReportRate(settings.Setting): name = "report_rate_extended" label = _("Report Rate") description = ( _("Frequency of device movement reports") + "\n" + _("May need Onboard Profiles set to Disable to be effective.") ) feature = _F.EXTENDED_ADJUSTABLE_REPORT_RATE rw_options = {"read_fnid": 0x20, "write_fnid": 0x30} choices_universe = common.NamedInts() choices_universe[0] = "8ms" choices_universe[1] = "4ms" choices_universe[2] = "2ms" choices_universe[3] = "1ms" choices_universe[4] = "500us" choices_universe[5] = "250us" choices_universe[6] = "125us" class validator_class(settings.ChoicesValidator): @classmethod def build(cls, setting_class, device): reply = device.feature_request(_F.EXTENDED_ADJUSTABLE_REPORT_RATE, 0x10) assert reply, "Oops, report rate choices cannot be retrieved!" rate_list = [] rate_flags = common.bytes2int(reply[0:2]) for i in range(0, 7): if rate_flags & (0x01 << i): rate_list.append(setting_class.choices_universe[i]) return cls(choices=common.NamedInts.list(rate_list), byte_count=1) if rate_list else None class DivertCrown(settings.Setting): name = "divert-crown" label = _("Divert crown events") description = _("Make crown send CROWN HID++ notifications (which trigger Solaar rules but are otherwise ignored).") feature = _F.CROWN rw_options = {"read_fnid": 0x10, "write_fnid": 0x20} validator_options = {"true_value": 0x02, "false_value": 0x01, "mask": 0xFF} class CrownSmooth(settings.Setting): name = "crown-smooth" label = _("Crown smooth scroll") description = _("Set crown smooth scroll") feature = _F.CROWN rw_options = {"read_fnid": 0x10, "write_fnid": 0x20} validator_options = {"true_value": 0x01, "false_value": 0x02, "read_skip_byte_count": 1, "write_prefix_bytes": b"\x00"} class DivertGkeys(settings.Setting): name = "divert-gkeys" label = _("Divert G and M Keys") description = _("Make G and M keys send HID++ notifications (which trigger Solaar rules but are otherwise ignored).") feature = _F.GKEY validator_options = {"true_value": 0x01, "false_value": 0x00, "mask": 0xFF} class rw_class(settings.FeatureRW): def __init__(self, feature): super().__init__(feature, write_fnid=0x20) def read(self, device): # no way to read, so just assume not diverted return b"\x00" class ScrollRatchet(settings.Setting): name = "scroll-ratchet" label = _("Scroll Wheel Ratcheted") description = _("Switch the mouse wheel between speed-controlled ratcheting and always freespin.") feature = _F.SMART_SHIFT choices_universe = common.NamedInts(**{_("Freespinning"): 1, _("Ratcheted"): 2}) validator_class = settings.ChoicesValidator validator_options = {"choices": choices_universe} class SmartShift(settings.Setting): name = "smart-shift" label = _("Scroll Wheel Ratchet Speed") description = _( "Use the mouse wheel speed to switch between ratcheted and freespinning.\n" "The mouse wheel is always ratcheted at 50." ) feature = _F.SMART_SHIFT rw_options = {"read_fnid": 0x00, "write_fnid": 0x10} class rw_class(settings.FeatureRW): MIN_VALUE = 1 MAX_VALUE = 50 def __init__(self, feature, read_fnid, write_fnid): super().__init__(feature, read_fnid, write_fnid) def read(self, device): value = super().read(device) if common.bytes2int(value[0:1]) == 1: # Mode = Freespin, map to minimum return common.int2bytes(self.MIN_VALUE, count=1) else: # Mode = smart shift, map to the value, capped at maximum threshold = min(common.bytes2int(value[1:2]), self.MAX_VALUE) return common.int2bytes(threshold, count=1) def write(self, device, data_bytes): threshold = common.bytes2int(data_bytes) # Freespin at minimum mode = 0 # 1 if threshold <= self.MIN_VALUE else 2 # Ratchet at maximum if threshold >= self.MAX_VALUE: threshold = 255 data = common.int2bytes(mode, count=1) + common.int2bytes(max(0, threshold), count=1) return super().write(device, data) min_value = rw_class.MIN_VALUE max_value = rw_class.MAX_VALUE validator_class = settings.RangeValidator class SmartShiftEnhanced(SmartShift): feature = _F.SMART_SHIFT_ENHANCED rw_options = {"read_fnid": 0x10, "write_fnid": 0x20} # the keys for the choice map are Logitech controls (from special_keys) # each choice value is a NamedInt with the string from a task (to be shown to the user) # and the integer being the control number for that task (to be written to the device) # Solaar only remaps keys (controlled by key gmask and group), not other key reprogramming class ReprogrammableKeys(settings.Settings): name = "reprogrammable-keys" label = _("Key/Button Actions") description = ( _("Change the action for the key or button.") + " " + _("Overridden by diversion.") + "\n" + _("Changing important actions (such as for the left mouse button) can result in an unusable system.") ) feature = _F.REPROG_CONTROLS_V4 keys_universe = special_keys.CONTROL choices_universe = special_keys.CONTROL class rw_class: def __init__(self, feature): self.feature = feature self.kind = settings.FeatureRW.kind def read(self, device, key): key_index = device.keys.index(key) key_struct = device.keys[key_index] return b"\x00\x00" + common.int2bytes(int(key_struct.mapped_to), 2) def write(self, device, key, data_bytes): key_index = device.keys.index(key) key_struct = device.keys[key_index] key_struct.remap(special_keys.CONTROL[common.bytes2int(data_bytes)]) return True class validator_class(settings.ChoicesMapValidator): @classmethod def build(cls, setting_class, device): choices = {} if device.keys: for k in device.keys: tgts = k.remappable_to if len(tgts) > 1: choices[k.key] = tgts return cls(choices, key_byte_count=2, byte_count=2, extra_default=0) if choices else None class DpiSlidingXY(settings.RawXYProcessing): def __init__( self, *args, show_notification: Callable[[str, str], bool], **kwargs, ): super().__init__(*args, **kwargs) self.fsmState = None self._show_notification = show_notification def activate_action(self): self.dpiSetting = next(filter(lambda s: s.name == "dpi" or s.name == "dpi_extended", self.device.settings), None) self.dpiChoices = list(self.dpiSetting.choices) self.otherDpiIdx = self.device.persister.get("_dpi-sliding", -1) if self.device.persister else -1 if not isinstance(self.otherDpiIdx, int) or self.otherDpiIdx < 0 or self.otherDpiIdx >= len(self.dpiChoices): self.otherDpiIdx = self.dpiChoices.index(self.dpiSetting.read()) self.fsmState = State.IDLE self.dx = 0.0 self.movingDpiIdx = None def setNewDpi(self, newDpiIdx): newDpi = self.dpiChoices[newDpiIdx] self.dpiSetting.write(newDpi) if self.device.setting_callback: self.device.setting_callback(self.device, type(self.dpiSetting), [newDpi]) def displayNewDpi(self, newDpiIdx): selected_dpi = self.dpiChoices[newDpiIdx] min_dpi = self.dpiChoices[0] max_dpi = self.dpiChoices[-1] reason = f"DPI {selected_dpi} [min {min_dpi}, max {max_dpi}]" self._show_notification(self.device, reason) def press_action(self, key): # start tracking self.starting = True if self.fsmState == State.IDLE: self.fsmState = State.PRESSED self.dx = 0.0 # While in 'moved' state, the index into 'dpiChoices' of the currently selected DPI setting self.movingDpiIdx = None def release_action(self): # adjust DPI and stop tracking if self.fsmState == State.PRESSED: # Swap with other DPI thisIdx = self.dpiChoices.index(self.dpiSetting.read()) newDpiIdx, self.otherDpiIdx = self.otherDpiIdx, thisIdx if self.device.persister: self.device.persister["_dpi-sliding"] = self.otherDpiIdx self.setNewDpi(newDpiIdx) self.displayNewDpi(newDpiIdx) elif self.fsmState == State.MOVED: # Set DPI according to displacement self.setNewDpi(self.movingDpiIdx) self.fsmState = State.IDLE def move_action(self, dx, dy): if self.device.features.get_feature_version(_F.REPROG_CONTROLS_V4) >= 5 and self.starting: self.starting = False # hack to ignore strange first movement report from MX Master 3S return currDpi = self.dpiSetting.read() self.dx += float(dx) / float(currDpi) * 15.0 # yields a more-or-less DPI-independent dx of about 5/cm if self.fsmState == State.PRESSED: if abs(self.dx) >= 1.0: self.fsmState = State.MOVED self.movingDpiIdx = self.dpiChoices.index(currDpi) elif self.fsmState == State.MOVED: currIdx = self.dpiChoices.index(self.dpiSetting.read()) newMovingDpiIdx = min(max(currIdx + int(self.dx), 0), len(self.dpiChoices) - 1) if newMovingDpiIdx != self.movingDpiIdx: self.movingDpiIdx = newMovingDpiIdx self.displayNewDpi(newMovingDpiIdx) class MouseGesturesXY(settings.RawXYProcessing): def activate_action(self): self.dpiSetting = next(filter(lambda s: s.name == "dpi" or s.name == "dpi_extended", self.device.settings), None) self.fsmState = State.IDLE self.initialize_data() def initialize_data(self): self.dx = 0.0 self.dy = 0.0 self.lastEv = None self.data = [] def press_action(self, key): self.starting = True if self.fsmState == State.IDLE: self.fsmState = State.PRESSED self.initialize_data() self.data = [key.key] def release_action(self): if self.fsmState == State.PRESSED: # emit mouse gesture notification self.push_mouse_event() if logger.isEnabledFor(logging.INFO): logger.info("mouse gesture notification %s", self.data) payload = struct.pack("!" + (len(self.data) * "h"), *self.data) notification = base.HIDPPNotification(0, 0, 0, 0, payload) diversion.process_notification(self.device, notification, _F.MOUSE_GESTURE) self.fsmState = State.IDLE def move_action(self, dx, dy): if self.fsmState == State.PRESSED: now = time() * 1000 # time_ns() / 1e6 if self.device.features.get_feature_version(_F.REPROG_CONTROLS_V4) >= 5 and self.starting: self.starting = False # hack to ignore strange first movement report from MX Master 3S return if self.lastEv is not None and now - self.lastEv > 200.0: self.push_mouse_event() dpi = self.dpiSetting.read() if self.dpiSetting else 1000 dx = float(dx) / float(dpi) * 15.0 # This multiplier yields a more-or-less DPI-independent dx of about 5/cm self.dx += dx dy = float(dy) / float(dpi) * 15.0 # This multiplier yields a more-or-less DPI-independent dx of about 5/cm self.dy += dy self.lastEv = now def key_action(self, key): self.push_mouse_event() self.data.append(1) self.data.append(key) self.lastEv = time() * 1000 # time_ns() / 1e6 if logger.isEnabledFor(logging.DEBUG): logger.debug("mouse gesture key event %d %s", key, self.data) def push_mouse_event(self): x = int(self.dx) y = int(self.dy) if x == 0 and y == 0: return self.data.append(0) self.data.append(x) self.data.append(y) self.dx = 0.0 self.dy = 0.0 if logger.isEnabledFor(logging.DEBUG): logger.debug("mouse gesture move event %d %d %s", x, y, self.data) class DivertKeys(settings.Settings): name = "divert-keys" label = _("Key/Button Diversion") description = _("Make the key or button send HID++ notifications (Diverted) or initiate Mouse Gestures or Sliding DPI") feature = _F.REPROG_CONTROLS_V4 keys_universe = special_keys.CONTROL choices_universe = common.NamedInts(**{_("Regular"): 0, _("Diverted"): 1, _("Mouse Gestures"): 2, _("Sliding DPI"): 3}) choices_gesture = common.NamedInts(**{_("Regular"): 0, _("Diverted"): 1, _("Mouse Gestures"): 2}) choices_divert = common.NamedInts(**{_("Regular"): 0, _("Diverted"): 1}) class rw_class: def __init__(self, feature): self.feature = feature self.kind = settings.FeatureRW.kind def read(self, device, key): key_index = device.keys.index(key) key_struct = device.keys[key_index] return b"\x00\x00\x01" if "diverted" in key_struct.mapping_flags else b"\x00\x00\x00" def write(self, device, key, data_bytes): key_index = device.keys.index(key) key_struct = device.keys[key_index] key_struct.set_diverted(common.bytes2int(data_bytes) != 0) # not regular return True class validator_class(settings.ChoicesMapValidator): def __init__(self, choices, key_byte_count=2, byte_count=1, mask=0x01): super().__init__(choices, key_byte_count, byte_count, mask) def prepare_write(self, key, new_value): if self.gestures and new_value != 2: # mouse gestures self.gestures.stop(key) if self.sliding and new_value != 3: # sliding DPI self.sliding.stop(key) if self.gestures and new_value == 2: # mouse gestures self.gestures.start(key) if self.sliding and new_value == 3: # sliding DPI self.sliding.start(key) return super().prepare_write(key, new_value) @classmethod def build(cls, setting_class, device): sliding = gestures = None choices = {} if device.keys: for k in device.keys: if "divertable" in k.flags and "virtual" not in k.flags: if "raw XY" in k.flags: choices[k.key] = setting_class.choices_gesture if gestures is None: gestures = MouseGesturesXY(device, name="MouseGestures") if _F.ADJUSTABLE_DPI in device.features: choices[k.key] = setting_class.choices_universe if sliding is None: sliding = DpiSlidingXY( device, name="DpiSliding", show_notification=desktop_notifications.show ) else: choices[k.key] = setting_class.choices_divert if not choices: return None validator = cls(choices, key_byte_count=2, byte_count=1, mask=0x01) validator.sliding = sliding validator.gestures = gestures return validator def produce_dpi_list(feature, function, ignore, device, direction): dpi_bytes = b"" for i in range(0, 0x100): # there will be only a very few iterations performed reply = device.feature_request(feature, function, 0x00, direction, i) assert reply, "Oops, DPI list cannot be retrieved!" dpi_bytes += reply[ignore:] if dpi_bytes[-2:] == b"\x00\x00": break dpi_list = [] i = 0 while i < len(dpi_bytes): val = common.bytes2int(dpi_bytes[i : i + 2]) if val == 0: break if val >> 13 == 0b111: step = val & 0x1FFF last = common.bytes2int(dpi_bytes[i + 2 : i + 4]) assert len(dpi_list) > 0 and last > dpi_list[-1], f"Invalid DPI list item: {val!r}" dpi_list += range(dpi_list[-1] + step, last + 1, step) i += 4 else: dpi_list.append(val) i += 2 return dpi_list class AdjustableDpi(settings.Setting): name = "dpi" label = _("Sensitivity (DPI)") description = _("Mouse movement sensitivity") feature = _F.ADJUSTABLE_DPI rw_options = {"read_fnid": 0x20, "write_fnid": 0x30} choices_universe = common.NamedInts.range(100, 4000, str, 50) class validator_class(settings.ChoicesValidator): @classmethod def build(cls, setting_class, device): dpilist = produce_dpi_list(setting_class.feature, 0x10, 1, device, 0) setting = ( cls(choices=common.NamedInts.list(dpilist), byte_count=2, write_prefix_bytes=b"\x00") if dpilist else None ) setting.dpilist = dpilist return setting def validate_read(self, reply_bytes): # special validator to use default DPI if needed reply_value = common.bytes2int(reply_bytes[1:3]) if reply_value == 0: # use default value instead reply_value = common.bytes2int(reply_bytes[3:5]) valid_value = self.choices[reply_value] assert valid_value is not None, f"{self.__class__.__name__}: failed to validate read value {reply_value:02X}" return valid_value class ExtendedAdjustableDpi(settings.Setting): # the extended version allows for two dimensions, longer dpi descriptions, but still assume only one sensor name = "dpi_extended" label = _("Sensitivity (DPI)") description = _("Mouse movement sensitivity") + "\n" + _("May need Onboard Profiles set to Disable to be effective.") feature = _F.EXTENDED_ADJUSTABLE_DPI rw_options = {"read_fnid": 0x50, "write_fnid": 0x60} keys_universe = common.NamedInts(X=0, Y=1, LOD=2) choices_universe = common.NamedInts.range(100, 4000, str, 50) choices_universe[0] = "LOW" choices_universe[1] = "MEDIUM" choices_universe[2] = "HIGH" keys = common.NamedInts(X=0, Y=1, LOD=2) def write_key_value(self, key, value, save=True): if isinstance(self._value, dict): self._value[key] = value else: self._value = {key: value} result = self.write(self._value, save) return result[key] if isinstance(result, dict) else result class validator_class(settings.ChoicesMapValidator): @classmethod def build(cls, setting_class, device): reply = device.feature_request(setting_class.feature, 0x10, 0x00) y = bool(reply[2] & 0x01) lod = bool(reply[2] & 0x02) choices_map = {} dpilist_x = produce_dpi_list(setting_class.feature, 0x20, 3, device, 0) choices_map[setting_class.keys["X"]] = common.NamedInts.list(dpilist_x) if y: dpilist_y = produce_dpi_list(setting_class.feature, 0x20, 3, device, 1) choices_map[setting_class.keys["Y"]] = common.NamedInts.list(dpilist_y) if lod: choices_map[setting_class.keys["LOD"]] = common.NamedInts(LOW=0, MEDIUM=1, HIGH=2) validator = cls(choices_map=choices_map, byte_count=2, write_prefix_bytes=b"\x00") validator.y = y validator.lod = lod validator.keys = setting_class.keys return validator def validate_read(self, reply_bytes): # special validator to read entire setting dpi_x = common.bytes2int(reply_bytes[3:5]) if reply_bytes[1:3] == 0 else common.bytes2int(reply_bytes[1:3]) assert dpi_x in self.choices[0], f"{self.__class__.__name__}: failed to validate dpi_x value {dpi_x:04X}" value = {self.keys["X"]: dpi_x} if self.y: dpi_y = common.bytes2int(reply_bytes[7:9]) if reply_bytes[5:7] == 0 else common.bytes2int(reply_bytes[5:7]) assert dpi_y in self.choices[1], f"{self.__class__.__name__}: failed to validate dpi_y value {dpi_y:04X}" value[self.keys["Y"]] = dpi_y if self.lod: lod = reply_bytes[9] assert lod in self.choices[2], f"{self.__class__.__name__}: failed to validate lod value {lod:02X}" value[self.keys["LOD"]] = lod return value def prepare_write(self, new_value, current_value=None): # special preparer to write entire setting data_bytes = self._write_prefix_bytes if new_value[self.keys["X"]] not in self.choices[self.keys["X"]]: raise ValueError(f"invalid value {new_value!r}") data_bytes += common.int2bytes(new_value[0], 2) if self.y: if new_value[self.keys["Y"]] not in self.choices[self.keys["Y"]]: raise ValueError(f"invalid value {new_value!r}") data_bytes += common.int2bytes(new_value[self.keys["Y"]], 2) else: data_bytes += b"\x00\x00" if self.lod: if new_value[self.keys["LOD"]] not in self.choices[self.keys["LOD"]]: raise ValueError(f"invalid value {new_value!r}") data_bytes += common.int2bytes(new_value[self.keys["LOD"]], 1) else: data_bytes += b"\x00" return data_bytes class SpeedChange(settings.Setting): """Implements the ability to switch Sensitivity by clicking on the DPI_Change button.""" name = "speed-change" label = _("Sensitivity Switching") description = _( "Switch the current sensitivity and the remembered sensitivity when the key or button is pressed.\n" "If there is no remembered sensitivity, just remember the current sensitivity" ) choices_universe = special_keys.CONTROL choices_extra = common.NamedInt(0, _("Off")) feature = _F.POINTER_SPEED rw_options = {"name": "speed change"} class rw_class(settings.ActionSettingRW): def press_action(self): # switch sensitivity currentSpeed = self.device.persister.get("pointer_speed", None) if self.device.persister else None newSpeed = self.device.persister.get("_speed-change", None) if self.device.persister else None speed_setting = next(filter(lambda s: s.name == "pointer_speed", self.device.settings), None) if newSpeed is not None: if speed_setting: speed_setting.write(newSpeed) if self.device.setting_callback: self.device.setting_callback(self.device, type(speed_setting), [newSpeed]) else: logger.error("cannot save sensitivity setting on %s", self.device) if self.device.persister: self.device.persister["_speed-change"] = currentSpeed class validator_class(settings.ChoicesValidator): @classmethod def build(cls, setting_class, device): key_index = device.keys.index(special_keys.CONTROL.DPI_Change) key = device.keys[key_index] if key_index is not None else None if key is not None and "divertable" in key.flags: keys = [setting_class.choices_extra, key.key] return cls(choices=common.NamedInts.list(keys), byte_count=2) class DisableKeyboardKeys(settings.BitFieldSetting): name = "disable-keyboard-keys" label = _("Disable keys") description = _("Disable specific keyboard keys.") feature = _F.KEYBOARD_DISABLE_KEYS rw_options = {"read_fnid": 0x10, "write_fnid": 0x20} _labels = {k: (None, _("Disables the %s key.") % k) for k in special_keys.DISABLE} choices_universe = special_keys.DISABLE class validator_class(settings.BitFieldValidator): @classmethod def build(cls, setting_class, device): mask = device.feature_request(_F.KEYBOARD_DISABLE_KEYS, 0x00)[0] options = [special_keys.DISABLE[1 << i] for i in range(8) if mask & (1 << i)] return cls(options) if options else None class Multiplatform(settings.Setting): name = "multiplatform" label = _("Set OS") description = _("Change keys to match OS.") feature = _F.MULTIPLATFORM rw_options = {"read_fnid": 0x00, "write_fnid": 0x30} choices_universe = common.NamedInts(**{"OS " + str(i + 1): i for i in range(8)}) # multiplatform OS bits OSS = [ ("Linux", 0x0400), ("MacOS", 0x2000), ("Windows", 0x0100), ("iOS", 0x4000), ("Android", 0x1000), ("WebOS", 0x8000), ("Chrome", 0x0800), ("WinEmb", 0x0200), ("Tizen", 0x0001), ] # the problem here is how to construct the right values for the rules Set GUI, # as, for example, the integer value for 'Windows' can be different on different devices class validator_class(settings.ChoicesValidator): @classmethod def build(cls, setting_class, device): def _str_os_versions(low, high): def _str_os_version(version): if version == 0: return "" elif version & 0xFF: return str(version >> 8) + "." + str(version & 0xFF) else: return str(version >> 8) return "" if low == 0 and high == 0 else " " + _str_os_version(low) + "-" + _str_os_version(high) infos = device.feature_request(_F.MULTIPLATFORM) assert infos, "Oops, multiplatform count cannot be retrieved!" flags, _ignore, num_descriptors = struct.unpack("!BBB", infos[:3]) if not (flags & 0x02): # can't set platform so don't create setting return [] descriptors = [] for index in range(0, num_descriptors): descriptor = device.feature_request(_F.MULTIPLATFORM, 0x10, index) platform, _ignore, os_flags, low, high = struct.unpack("!BBHHH", descriptor[:8]) descriptors.append((platform, os_flags, low, high)) choices = common.NamedInts() for os_name, os_bit in setting_class.OSS: for platform, os_flags, low, high in descriptors: os = os_name + _str_os_versions(low, high) if os_bit & os_flags and platform not in choices and os not in choices: choices[platform] = os return cls(choices=choices, read_skip_byte_count=6, write_prefix_bytes=b"\xff") if choices else None class DualPlatform(settings.Setting): name = "multiplatform" label = _("Set OS") description = _("Change keys to match OS.") choices_universe = common.NamedInts() choices_universe[0x00] = "iOS, MacOS" choices_universe[0x01] = "Android, Windows" feature = _F.DUALPLATFORM rw_options = {"read_fnid": 0x00, "write_fnid": 0x20} validator_class = settings.ChoicesValidator validator_options = {"choices": choices_universe} class ChangeHost(settings.Setting): name = "change-host" label = _("Change Host") description = _("Switch connection to a different host") persist = False # persisting this setting is harmful feature = _F.CHANGE_HOST rw_options = {"read_fnid": 0x00, "write_fnid": 0x10, "no_reply": True} choices_universe = common.NamedInts(**{"Host " + str(i + 1): i for i in range(3)}) class validator_class(settings.ChoicesValidator): @classmethod def build(cls, setting_class, device): infos = device.feature_request(_F.CHANGE_HOST) assert infos, "Oops, host count cannot be retrieved!" numHosts, currentHost = struct.unpack("!BB", infos[:2]) hostNames = _hidpp20.get_host_names(device) hostNames = hostNames if hostNames is not None else {} if currentHost not in hostNames or hostNames[currentHost][1] == "": hostNames[currentHost] = (True, socket.gethostname().partition(".")[0]) choices = common.NamedInts() for host in range(0, numHosts): paired, hostName = hostNames.get(host, (True, "")) choices[host] = str(host + 1) + ":" + hostName if hostName else str(host + 1) return cls(choices=choices, read_skip_byte_count=1) if choices and len(choices) > 1 else None _GESTURE2_GESTURES_LABELS = { _GG["Tap1Finger"]: (_("Single tap"), _("Performs a left click.")), _GG["Tap2Finger"]: (_("Single tap with two fingers"), _("Performs a right click.")), _GG["Tap3Finger"]: (_("Single tap with three fingers"), None), _GG["Click1Finger"]: (None, None), _GG["Click2Finger"]: (None, None), _GG["Click3Finger"]: (None, None), _GG["DoubleTap1Finger"]: (_("Double tap"), _("Performs a double click.")), _GG["DoubleTap2Finger"]: (_("Double tap with two fingers"), None), _GG["DoubleTap3Finger"]: (_("Double tap with three fingers"), None), _GG["Track1Finger"]: (None, None), _GG["TrackingAcceleration"]: (None, None), _GG["TapDrag1Finger"]: (_("Tap and drag"), _("Drags items by dragging the finger after double tapping.")), _GG["TapDrag2Finger"]: ( _("Tap and drag with two fingers"), _("Drags items by dragging the fingers after double tapping."), ), _GG["Drag3Finger"]: (_("Tap and drag with three fingers"), None), _GG["TapGestures"]: (None, None), _GG["FnClickGestureSuppression"]: ( _("Suppress tap and edge gestures"), _("Disables tap and edge gestures (equivalent to pressing Fn+LeftClick)."), ), _GG["Scroll1Finger"]: (_("Scroll with one finger"), _("Scrolls.")), _GG["Scroll2Finger"]: (_("Scroll with two fingers"), _("Scrolls.")), _GG["Scroll2FingerHoriz"]: (_("Scroll horizontally with two fingers"), _("Scrolls horizontally.")), _GG["Scroll2FingerVert"]: (_("Scroll vertically with two fingers"), _("Scrolls vertically.")), _GG["Scroll2FingerStateless"]: (_("Scroll with two fingers"), _("Scrolls.")), _GG["NaturalScrolling"]: (_("Natural scrolling"), _("Inverts the scrolling direction.")), _GG["Thumbwheel"]: (_("Thumbwheel"), _("Enables the thumbwheel.")), _GG["VScrollInertia"]: (None, None), _GG["VScrollBallistics"]: (None, None), _GG["Swipe2FingerHoriz"]: (None, None), _GG["Swipe3FingerHoriz"]: (None, None), _GG["Swipe4FingerHoriz"]: (None, None), _GG["Swipe3FingerVert"]: (None, None), _GG["Swipe4FingerVert"]: (None, None), _GG["LeftEdgeSwipe1Finger"]: (None, None), _GG["RightEdgeSwipe1Finger"]: (None, None), _GG["BottomEdgeSwipe1Finger"]: (None, None), _GG["TopEdgeSwipe1Finger"]: (_("Swipe from the top edge"), None), _GG["LeftEdgeSwipe1Finger2"]: (_("Swipe from the left edge"), None), _GG["RightEdgeSwipe1Finger2"]: (_("Swipe from the right edge"), None), _GG["BottomEdgeSwipe1Finger2"]: (_("Swipe from the bottom edge"), None), _GG["TopEdgeSwipe1Finger2"]: (_("Swipe from the top edge"), None), _GG["LeftEdgeSwipe2Finger"]: (_("Swipe two fingers from the left edge"), None), _GG["RightEdgeSwipe2Finger"]: (_("Swipe two fingers from the right edge"), None), _GG["BottomEdgeSwipe2Finger"]: (_("Swipe two fingers from the bottom edge"), None), _GG["TopEdgeSwipe2Finger"]: (_("Swipe two fingers from the top edge"), None), _GG["Zoom2Finger"]: (_("Zoom with two fingers."), _("Pinch to zoom out; spread to zoom in.")), _GG["Zoom2FingerPinch"]: (_("Pinch to zoom out."), _("Pinch to zoom out.")), _GG["Zoom2FingerSpread"]: (_("Spread to zoom in."), _("Spread to zoom in.")), _GG["Zoom3Finger"]: (_("Zoom with three fingers."), None), _GG["Zoom2FingerStateless"]: (_("Zoom with two fingers"), _("Pinch to zoom out; spread to zoom in.")), _GG["TwoFingersPresent"]: (None, None), _GG["Rotate2Finger"]: (None, None), _GG["Finger1"]: (None, None), _GG["Finger2"]: (None, None), _GG["Finger3"]: (None, None), _GG["Finger4"]: (None, None), _GG["Finger5"]: (None, None), _GG["Finger6"]: (None, None), _GG["Finger7"]: (None, None), _GG["Finger8"]: (None, None), _GG["Finger9"]: (None, None), _GG["Finger10"]: (None, None), _GG["DeviceSpecificRawData"]: (None, None), } _GESTURE2_PARAMS_LABELS = { _GP["ExtraCapabilities"]: (None, None), # not supported _GP["PixelZone"]: (_("Pixel zone"), None), # TO DO: replace None with a short description _GP["RatioZone"]: (_("Ratio zone"), None), # TO DO: replace None with a short description _GP["ScaleFactor"]: (_("Scale factor"), _("Sets the cursor speed.")), } _GESTURE2_PARAMS_LABELS_SUB = { "left": (_("Left"), _("Left-most coordinate.")), "bottom": (_("Bottom"), _("Bottom coordinate.")), "width": (_("Width"), _("Width.")), "height": (_("Height"), _("Height.")), "scale": (_("Scale"), _("Cursor speed.")), } class Gesture2Gestures(settings.BitFieldWithOffsetAndMaskSetting): name = "gesture2-gestures" label = _("Gestures") description = _("Tweak the mouse/touchpad behaviour.") feature = _F.GESTURE_2 rw_options = {"read_fnid": 0x10, "write_fnid": 0x20} validator_options = {"om_method": hidpp20.Gesture.enable_offset_mask} choices_universe = hidpp20_constants.GESTURE _labels = _GESTURE2_GESTURES_LABELS class validator_class(settings.BitFieldWithOffsetAndMaskValidator): @classmethod def build(cls, setting_class, device, om_method=None): options = [g for g in device.gestures.gestures.values() if g.can_be_enabled or g.default_enabled] return cls(options, om_method=om_method) if options else None class Gesture2Divert(settings.BitFieldWithOffsetAndMaskSetting): name = "gesture2-divert" label = _("Gestures Diversion") description = _("Divert mouse/touchpad gestures.") feature = _F.GESTURE_2 rw_options = {"read_fnid": 0x30, "write_fnid": 0x40} validator_options = {"om_method": hidpp20.Gesture.diversion_offset_mask} choices_universe = hidpp20_constants.GESTURE _labels = _GESTURE2_GESTURES_LABELS class validator_class(settings.BitFieldWithOffsetAndMaskValidator): @classmethod def build(cls, setting_class, device, om_method=None): options = [g for g in device.gestures.gestures.values() if g.can_be_diverted] return cls(options, om_method=om_method) if options else None class Gesture2Params(settings.LongSettings): name = "gesture2-params" label = _("Gesture params") description = _("Change numerical parameters of a mouse/touchpad.") feature = _F.GESTURE_2 rw_options = {"read_fnid": 0x70, "write_fnid": 0x80} choices_universe = hidpp20.PARAM sub_items_universe = hidpp20.SUB_PARAM # item (NamedInt) -> list/tuple of objects that have the following attributes # .id (sub-item text), .length (in bytes), .minimum and .maximum _labels = _GESTURE2_PARAMS_LABELS _labels_sub = _GESTURE2_PARAMS_LABELS_SUB class validator_class(settings.MultipleRangeValidator): @classmethod def build(cls, setting_class, device): params = _hidpp20.get_gestures(device).params.values() items = [i for i in params if i.sub_params] if not items: return None sub_items = {i: i.sub_params for i in items} return cls(items, sub_items) class MKeyLEDs(settings.BitFieldSetting): name = "m-key-leds" label = _("M-Key LEDs") description = ( _("Control the M-Key LEDs.") + "\n" + _("May need Onboard Profiles set to Disable to be effective.") + "\n" + _("May need G Keys diverted to be effective.") ) feature = _F.MKEYS choices_universe = common.NamedInts() for i in range(8): choices_universe[1 << i] = "M" + str(i + 1) _labels = {k: (None, _("Lights up the %s key.") % k) for k in choices_universe} class rw_class(settings.FeatureRW): def __init__(self, feature): super().__init__(feature, write_fnid=0x10) def read(self, device): # no way to read, so just assume off return b"\x00" class validator_class(settings.BitFieldValidator): @classmethod def build(cls, setting_class, device): number = device.feature_request(setting_class.feature, 0x00)[0] options = [setting_class.choices_universe[1 << i] for i in range(number)] return cls(options) if options else None class MRKeyLED(settings.Setting): name = "mr-key-led" label = _("MR-Key LED") description = ( _("Control the MR-Key LED.") + "\n" + _("May need Onboard Profiles set to Disable to be effective.") + "\n" + _("May need G Keys diverted to be effective.") ) feature = _F.MR class rw_class(settings.FeatureRW): def __init__(self, feature): super().__init__(feature, write_fnid=0x00) def read(self, device): # no way to read, so just assume off return b"\x00" ## Only implemented for devices that can produce Key and Consumer Codes (e.g., Craft) ## and devices that can produce Key, Mouse, and Horizontal Scroll (e.g., M720) ## Only interested in current host, so use 0xFF for it class PersistentRemappableAction(settings.Settings): name = "persistent-remappable-keys" label = _("Persistent Key/Button Mapping") description = ( _("Permanently change the mapping for the key or button.") + "\n" + _("Changing important keys or buttons (such as for the left mouse button) can result in an unusable system.") ) persist = False # This setting is persistent in the device so no need to persist it here feature = _F.PERSISTENT_REMAPPABLE_ACTION keys_universe = special_keys.CONTROL choices_universe = special_keys.KEYS class rw_class: def __init__(self, feature): self.feature = feature self.kind = settings.FeatureRW.kind def read(self, device, key): ks = device.remap_keys[device.remap_keys.index(key)] return b"\x00\x00" + ks.data_bytes def write(self, device, key, data_bytes): ks = device.remap_keys[device.remap_keys.index(key)] v = ks.remap(data_bytes) return v class validator_class(settings.ChoicesMapValidator): @classmethod def build(cls, setting_class, device): remap_keys = device.remap_keys if not remap_keys: return None capabilities = device.remap_keys.capabilities if capabilities & 0x0041 == 0x0041: # Key and Consumer Codes keys = special_keys.KEYS_KEYS_CONSUMER elif capabilities & 0x0023 == 0x0023: # Key, Mouse, and HScroll Codes keys = special_keys.KEYS_KEYS_MOUSE_HSCROLL else: if logger.isEnabledFor(logging.WARNING): logger.warning("%s: unimplemented Persistent Remappable capability %s", device.name, hex(capabilities)) return None choices = {} for k in remap_keys: if k is not None: key = special_keys.CONTROL[k.key] choices[key] = keys # TO RECOVER FROM BAD VALUES use special_keys.KEYS return cls(choices, key_byte_count=2, byte_count=4) if choices else None def validate_read(self, reply_bytes, key): start = self._key_byte_count + self._read_skip_byte_count end = start + self._byte_count reply_value = common.bytes2int(reply_bytes[start:end]) & self.mask # Craft keyboard has a value that isn't valid so fudge these values if reply_value not in self.choices[key]: if logger.isEnabledFor(logging.WARNING): logger.warning("unusual persistent remappable action mapping %x: use Default", reply_value) reply_value = special_keys.KEYS_Default return reply_value class Sidetone(settings.Setting): name = "sidetone" label = _("Sidetone") description = _("Set sidetone level.") feature = _F.SIDETONE validator_class = settings.RangeValidator min_value = 0 max_value = 100 class Equalizer(settings.RangeFieldSetting): name = "equalizer" label = _("Equalizer") description = _("Set equalizer levels.") feature = _F.EQUALIZER rw_options = {"read_fnid": 0x20, "write_fnid": 0x30, "read_prefix": b"\x00"} keys_universe = [] class validator_class(settings.PackedRangeValidator): @classmethod def build(cls, setting_class, device): data = device.feature_request(_F.EQUALIZER, 0x00) if not data: return None count, dbRange, _x, dbMin, dbMax = struct.unpack("!BBBBB", data[:5]) if dbMin == 0: dbMin = -dbRange if dbMax == 0: dbMax = dbRange map = common.NamedInts() for g in range((count + 6) // 7): freqs = device.feature_request(_F.EQUALIZER, 0x10, g * 7) for b in range(7): if g * 7 + b >= count: break map[g * 7 + b] = str(int.from_bytes(freqs[2 * b + 1 : 2 * b + 3], "big")) + _("Hz") return cls(map, min_value=dbMin, max_value=dbMax, count=count, write_prefix_bytes=b"\x02") class ADCPower(settings.Setting): name = "adc_power_management" label = _("Power Management") description = _("Power off in minutes (0 for never).") feature = _F.ADC_MEASUREMENT rw_options = {"read_fnid": 0x10, "write_fnid": 0x20} validator_class = settings.RangeValidator min_value = 0x00 max_value = 0xFF validator_options = {"byte_count": 1} class BrightnessControl(settings.Setting): name = "brightness_control" label = _("Brightness Control") description = _("Control overall brightness") feature = _F.BRIGHTNESS_CONTROL rw_options = {"read_fnid": 0x10, "write_fnid": 0x20} validator_class = settings.RangeValidator def __init__(self, device, rw, validator): super().__init__(device, rw, validator) rw.on_off = validator.on_off rw.min_nonzero_value = validator.min_value validator.min_value = 0 if validator.on_off else validator.min_value class rw_class(settings.FeatureRW): def read(self, device, data_bytes=b""): if self.on_off: reply = device.feature_request(self.feature, 0x30) if not reply[0] & 0x01: return b"\x00\x00" return super().read(device, data_bytes) def write(self, device, data_bytes): if self.on_off: off = int.from_bytes(data_bytes, byteorder="big") < self.min_nonzero_value reply = device.feature_request(self.feature, 0x40, b"\x00" if off else b"\x01", no_reply=False) if off: return reply return super().write(device, data_bytes) class validator_class(settings.RangeValidator): @classmethod def build(cls, setting_class, device): reply = device.feature_request(_F.BRIGHTNESS_CONTROL) assert reply, "Oops, brightness range cannot be retrieved!" if reply: max_value = int.from_bytes(reply[0:2], byteorder="big") min_value = int.from_bytes(reply[4:6], byteorder="big") on_off = bool(reply[3] & 0x04) # separate on/off control validator = cls(min_value=min_value, max_value=max_value, byte_count=2) validator.on_off = on_off return validator class LEDControl(settings.Setting): name = "led_control" label = _("LED Control") description = _("Switch control of LED zones between device and Solaar") feature = _F.COLOR_LED_EFFECTS rw_options = {"read_fnid": 0x70, "write_fnid": 0x80} choices_universe = common.NamedInts(Device=0, Solaar=1) validator_class = settings.ChoicesValidator validator_options = {"choices": choices_universe} colors = special_keys.COLORS _LEDP = hidpp20.LEDParam # an LED Zone has an index, a set of possible LED effects, and an LED effect setting class LEDZoneSetting(settings.Setting): name = "led_zone_" label = _("LED Zone Effects") description = _("Set effect for LED Zone") + "\n" + _("LED Control needs to be set to Solaar to be effective.") feature = _F.COLOR_LED_EFFECTS color_field = {"name": _LEDP.color, "kind": settings.KIND.choice, "label": None, "choices": colors} speed_field = {"name": _LEDP.speed, "kind": settings.KIND.range, "label": _("Speed"), "min": 0, "max": 255} period_field = {"name": _LEDP.period, "kind": settings.KIND.range, "label": _("Period"), "min": 100, "max": 5000} intensity_field = {"name": _LEDP.intensity, "kind": settings.KIND.range, "label": _("Intensity"), "min": 0, "max": 100} ramp_field = {"name": _LEDP.ramp, "kind": settings.KIND.choice, "label": _("Ramp"), "choices": hidpp20.LEDRampChoices} # form_field = {"name": _LEDP.form, "kind": settings.KIND.choice, "label": _("Form"), "choices": _hidpp20.LEDFormChoices} possible_fields = [color_field, speed_field, period_field, intensity_field, ramp_field] @classmethod def setup(cls, device, read_fnid, write_fnid, suffix): infos = device.led_effects settings_ = [] for zone in infos.zones: prefix = common.int2bytes(zone.index, 1) rw = settings.FeatureRW(cls.feature, read_fnid, write_fnid, prefix=prefix, suffix=suffix) validator = settings.HeteroValidator( data_class=hidpp20.LEDEffectSetting, options=zone.effects, readable=infos.readable ) setting = cls(device, rw, validator) setting.name = cls.name + str(int(zone.location)) setting.label = _("LEDs") + " " + str(hidpp20.LEDZoneLocations[zone.location]) choices = [hidpp20.LEDEffects[e.ID][0] for e in zone.effects if e.ID in hidpp20.LEDEffects] ID_field = {"name": "ID", "kind": settings.KIND.choice, "label": None, "choices": choices} setting.possible_fields = [ID_field] + cls.possible_fields setting.fields_map = hidpp20.LEDEffects settings_.append(setting) return settings_ @classmethod def build(cls, device): return cls.setup(device, 0xE0, 0x30, b"") class RGBControl(settings.Setting): name = "rgb_control" label = _("LED Control") description = _("Switch control of LED zones between device and Solaar") feature = _F.RGB_EFFECTS rw_options = {"read_fnid": 0x50, "write_fnid": 0x50} choices_universe = common.NamedInts(Device=0, Solaar=1) validator_class = settings.ChoicesValidator validator_options = {"choices": choices_universe, "write_prefix_bytes": b"\x01", "read_skip_byte_count": 1} class RGBEffectSetting(LEDZoneSetting): name = "rgb_zone_" label = _("LED Zone Effects") description = _("Set effect for LED Zone") + "\n" + _("LED Control needs to be set to Solaar to be effective.") feature = _F.RGB_EFFECTS @classmethod def build(cls, device): return cls.setup(device, 0xE0, 0x10, b"\x01") class PerKeyLighting(settings.Settings): name = "per-key-lighting" label = _("Per-key Lighting") description = _("Control per-key lighting.") feature = _F.PER_KEY_LIGHTING_V2 keys_universe = special_keys.KEYCODES choices_universe = special_keys.COLORSPLUS def read(self, cached=True): self._pre_read(cached) if cached and self._value is not None: return self._value reply_map = {} for key in self._validator.choices: reply_map[int(key)] = special_keys.COLORSPLUS["No change"] # this signals no change self._value = reply_map return reply_map def write(self, map, save=True): if self._device.online: self.update(map, save) table = {} for key, value in map.items(): if value in table: table[value].append(key) # keys will be in order from small to large else: table[value] = [key] if len(table) == 1: # use range update for value, keys in table.items(): # only one, of course if value != special_keys.COLORSPLUS["No change"]: # this signals no change, so don't update at all data_bytes = keys[0].to_bytes(1, "big") + keys[-1].to_bytes(1, "big") + value.to_bytes(3, "big") self._device.feature_request(self.feature, 0x50, data_bytes) # range update command to update all keys self._device.feature_request(self.feature, 0x70, 0x00) # signal device to make the changes else: data_bytes = b"" for value, keys in table.items(): # only one, of course if value != special_keys.COLORSPLUS["No change"]: # this signals no change, so ignore it while len(keys) > 3: # use an optimized update command that can update up to 13 keys data = value.to_bytes(3, "big") + b"".join([key.to_bytes(1, "big") for key in keys[0:13]]) self._device.feature_request(self.feature, 0x60, data) # single-value multiple-keys update keys = keys[13:] for key in keys: data_bytes += key.to_bytes(1, "big") + value.to_bytes(3, "big") if len(data_bytes) >= 16: # up to four values are packed into a regular update self._device.feature_request(self.feature, 0x10, data_bytes) data_bytes = b"" if len(data_bytes) > 0: # update any remaining keys self._device.feature_request(self.feature, 0x10, data_bytes) self._device.feature_request(self.feature, 0x70, 0x00) # signal device to make the changes return map def write_key_value(self, key, value, save=True): if value != special_keys.COLORSPLUS["No change"]: # this signals no change result = super().write_key_value(int(key), value, save) if self._device.online: self._device.feature_request(self.feature, 0x70, 0x00) # signal device to make the change return result else: return True class rw_class(settings.FeatureRWMap): pass class validator_class(settings.ChoicesMapValidator): @classmethod def build(cls, setting_class, device): choices_map = {} key_bitmap = device.feature_request(setting_class.feature, 0x00, 0x00, 0x00)[2:] key_bitmap += device.feature_request(setting_class.feature, 0x00, 0x00, 0x01)[2:] key_bitmap += device.feature_request(setting_class.feature, 0x00, 0x00, 0x02)[2:] for i in range(1, 255): if (key_bitmap[i // 8] >> i % 8) & 0x01: key = ( setting_class.keys_universe[i] if i in setting_class.keys_universe else common.NamedInt(i, "KEY " + str(i)) ) choices_map[key] = setting_class.choices_universe result = cls(choices_map) if choices_map else None return result SETTINGS = [ RegisterHandDetection, # simple RegisterSmoothScroll, # simple RegisterSideScroll, # simple RegisterDpi, RegisterFnSwap, # working HiResScroll, # simple LowresMode, # simple HiresSmoothInvert, # working HiresSmoothResolution, # working HiresMode, # simple ScrollRatchet, # simple SmartShift, # working SmartShiftEnhanced, # simple ThumbInvert, # working ThumbMode, # working OnboardProfiles, ReportRate, # working ExtendedReportRate, PointerSpeed, # simple AdjustableDpi, # working ExtendedAdjustableDpi, SpeedChange, # Backlight, # not working - disabled temporarily Backlight2, # working Backlight2Level, Backlight2DurationHandsOut, Backlight2DurationHandsIn, Backlight2DurationPowered, Backlight3, LEDControl, LEDZoneSetting, RGBControl, RGBEffectSetting, BrightnessControl, PerKeyLighting, FnSwap, # simple NewFnSwap, # simple K375sFnSwap, # working ReprogrammableKeys, # working PersistentRemappableAction, DivertKeys, # working DisableKeyboardKeys, # working CrownSmooth, # working DivertCrown, # working DivertGkeys, # working MKeyLEDs, # working MRKeyLED, # working Multiplatform, # working DualPlatform, # simple ChangeHost, # working Gesture2Gestures, # working Gesture2Divert, Gesture2Params, # working Sidetone, Equalizer, ADCPower, ] def check_feature(device, settings_class: settings.Setting) -> None | bool | Any: if settings_class.feature not in device.features: return if settings_class.min_version > device.features.get_feature_version(settings_class.feature): return try: detected = settings_class.build(device) if logger.isEnabledFor(logging.DEBUG): logger.debug("check_feature %s [%s] detected %s", settings_class.name, settings_class.feature, detected) return detected except Exception as e: logger.error( "check_feature %s [%s] error %s\n%s", settings_class.name, settings_class.feature, e, traceback.format_exc() ) return False # differentiate from an error-free determination that the setting is not supported # Returns True if device was queried to find features, False otherwise def check_feature_settings(device, already_known): """Auto-detect device settings by the HID++ 2.0 features they have.""" if not device.features or not device.online: return False if device.protocol and device.protocol < 2.0: return False absent = device.persister.get("_absent", []) if device.persister else [] newAbsent = [] for sclass in SETTINGS: if sclass.feature: known_present = device.persister and sclass.name in device.persister if not any(s.name == sclass.name for s in already_known) and (known_present or sclass.name not in absent): setting = check_feature(device, sclass) if isinstance(setting, list): for s in setting: already_known.append(s) if sclass.name in newAbsent: newAbsent.remove(sclass.name) elif setting: already_known.append(setting) if sclass.name in newAbsent: newAbsent.remove(sclass.name) elif setting is None: if sclass.name not in newAbsent and sclass.name not in absent and sclass.name not in device.persister: newAbsent.append(sclass.name) if device.persister and newAbsent: absent.extend(newAbsent) device.persister["_absent"] = absent return True def check_feature_setting(device, setting_name): for sclass in SETTINGS: if sclass.feature and sclass.name == setting_name and device.features: setting = check_feature(device, sclass) if setting: return setting
81,339
Python
.py
1,607
41.943995
127
0.641488
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,470
exceptions.py
pwr-Solaar_Solaar/lib/logitech_receiver/exceptions.py
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/ ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from .common import KwException """Exceptions that may be raised by this API.""" class NoReceiver(KwException): """Raised when trying to talk through a previously open handle, when the receiver is no longer available. Should only happen if the receiver is physically disconnected from the machine, or its kernel driver module is unloaded.""" pass class NoSuchDevice(KwException): """Raised when trying to reach a device number not paired to the receiver.""" pass class DeviceUnreachable(KwException): """Raised when a request is made to an unreachable (turned off) device.""" pass class FeatureNotSupported(KwException): """Raised when trying to request a feature not supported by the device.""" pass class FeatureCallError(KwException): """Raised if the device replied to a feature call with an error.""" pass
1,726
Python
.py
36
45.027778
84
0.760311
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,471
notifications.py
pwr-Solaar_Solaar/lib/logitech_receiver/notifications.py
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/ ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """Handles incoming events from the receiver/devices, updating the object as appropriate. """ from __future__ import annotations import logging import struct import threading import typing from solaar.i18n import _ from . import base from . import common from . import diversion from . import hidpp10 from . import hidpp10_constants from . import hidpp20 from . import hidpp20_constants from . import settings_templates from .common import Alert from .common import BatteryStatus from .common import Notification from .hidpp10_constants import Registers if typing.TYPE_CHECKING: from .base import HIDPPNotification from .receiver import Receiver logger = logging.getLogger(__name__) _hidpp10 = hidpp10.Hidpp10() _hidpp20 = hidpp20.Hidpp20() _F = hidpp20_constants.SupportedFeature notification_lock = threading.Lock() def process(device, notification): assert device assert notification if not device.isDevice: return _process_receiver_notification(device, notification) return _process_device_notification(device, notification) def _process_receiver_notification(receiver: Receiver, hidpp_notification: HIDPPNotification) -> bool | None: # supposedly only 0x4x notifications arrive for the receiver assert hidpp_notification.sub_id in [ Notification.CONNECT_DISCONNECT, Notification.DJ_PAIRING, Notification.CONNECTED, Notification.RAW_INPUT, Notification.PAIRING_LOCK, Notification.POWER, Registers.DEVICE_DISCOVERY_NOTIFICATION, Registers.DISCOVERY_STATUS_NOTIFICATION, Registers.PAIRING_STATUS_NOTIFICATION, Registers.PASSKEY_PRESSED_NOTIFICATION, Registers.PASSKEY_REQUEST_NOTIFICATION, ] if hidpp_notification.sub_id == Notification.PAIRING_LOCK: receiver.pairing.lock_open = bool(hidpp_notification.address & 0x01) reason = _("pairing lock is open") if receiver.pairing.lock_open else _("pairing lock is closed") if logger.isEnabledFor(logging.INFO): logger.info("%s: %s", receiver, reason) receiver.pairing.error = None if receiver.pairing.lock_open: receiver.pairing.new_device = None pair_error = ord(hidpp_notification.data[:1]) if pair_error: receiver.pairing.error = error_string = hidpp10_constants.PairingError(pair_error) receiver.pairing.new_device = None logger.warning("pairing error %d: %s", pair_error, error_string) receiver.changed(reason=reason) return True elif hidpp_notification.sub_id == Registers.DISCOVERY_STATUS_NOTIFICATION: # Bolt pairing with notification_lock: receiver.pairing.discovering = hidpp_notification.address == 0x00 reason = _("discovery lock is open") if receiver.pairing.discovering else _("discovery lock is closed") if logger.isEnabledFor(logging.INFO): logger.info("%s: %s", receiver, reason) receiver.pairing.error = None if receiver.pairing.discovering: receiver.pairing.counter = receiver.pairing.device_address = None receiver.pairing.device_authentication = receiver.pairing.device_name = None receiver.pairing.device_passkey = None discover_error = ord(hidpp_notification.data[:1]) if discover_error: receiver.pairing.error = discover_string = hidpp10_constants.BoltPairingError(discover_error) logger.warning("bolt discovering error %d: %s", discover_error, discover_string) receiver.changed(reason=reason) return True elif hidpp_notification.sub_id == Registers.DEVICE_DISCOVERY_NOTIFICATION: # Bolt pairing with notification_lock: counter = hidpp_notification.address + hidpp_notification.data[0] * 256 # notification counter if receiver.pairing.counter is None: receiver.pairing.counter = counter else: if not receiver.pairing.counter == counter: return None if hidpp_notification.data[1] == 0: receiver.pairing.device_kind = hidpp_notification.data[3] receiver.pairing.device_address = hidpp_notification.data[6:12] receiver.pairing.device_authentication = hidpp_notification.data[14] elif hidpp_notification.data[1] == 1: receiver.pairing.device_name = hidpp_notification.data[3 : 3 + hidpp_notification.data[2]].decode("utf-8") return True elif hidpp_notification.sub_id == Registers.PAIRING_STATUS_NOTIFICATION: # Bolt pairing with notification_lock: receiver.pairing.device_passkey = None receiver.pairing.lock_open = hidpp_notification.address == 0x00 reason = _("pairing lock is open") if receiver.pairing.lock_open else _("pairing lock is closed") if logger.isEnabledFor(logging.INFO): logger.info("%s: %s", receiver, reason) receiver.pairing.error = None if not receiver.pairing.lock_open: receiver.pairing.counter = None receiver.pairing.device_address = None receiver.pairing.device_authentication = None receiver.pairing.device_name = None pair_error = hidpp_notification.data[0] if receiver.pairing.lock_open: receiver.pairing.new_device = None elif hidpp_notification.address == 0x02 and not pair_error: receiver.pairing.new_device = receiver.register_new_device(hidpp_notification.data[7]) if pair_error: receiver.pairing.error = error_string = hidpp10_constants.BoltPairingError(pair_error) receiver.pairing.new_device = None logger.warning("pairing error %d: %s", pair_error, error_string) receiver.changed(reason=reason) return True elif hidpp_notification.sub_id == Registers.PASSKEY_REQUEST_NOTIFICATION: # Bolt pairing with notification_lock: receiver.pairing.device_passkey = hidpp_notification.data[0:6].decode("utf-8") return True elif hidpp_notification.sub_id == Registers.PASSKEY_PRESSED_NOTIFICATION: # Bolt pairing return True logger.warning("%s: unhandled notification %s", receiver, hidpp_notification) def _process_device_notification(device, n): # incoming packets with SubId >= 0x80 are supposedly replies from HID++ 1.0 requests, should never get here assert n.sub_id & 0x80 == 0 if n.sub_id == Notification.NO_OPERATION: # dispose it return False # Allow the device object to handle the notification using custom per-device state. handling_ret = device.handle_notification(n) if handling_ret is not None: return handling_ret # 0x40 to 0x7F appear to be HID++ 1.0 or DJ notifications if n.sub_id >= 0x40: if n.report_id == base.DJ_MESSAGE_ID: return _process_dj_notification(device, n) else: return _process_hidpp10_notification(device, n) # These notifications are from the device itself, so it must be active device.online = True # At this point, we need to know the device's protocol, otherwise it's possible to not know how to handle it. assert device.protocol is not None # some custom battery events for HID++ 1.0 devices if device.protocol < 2.0: return _process_hidpp10_custom_notification(device, n) # assuming 0x00 to 0x3F are feature (HID++ 2.0) notifications if not device.features: logger.warning("%s: feature notification but features not set up: %02X %s", device, n.sub_id, n) return False try: feature = device.features.get_feature(n.sub_id) except IndexError: logger.warning("%s: notification from invalid feature index %02X: %s", device, n.sub_id, n) return False return _process_feature_notification(device, n, feature) def _process_dj_notification(device, n): if logger.isEnabledFor(logging.DEBUG): logger.debug("%s (%s) DJ %s", device, device.protocol, n) if n.sub_id == Notification.CONNECT_DISCONNECT: # do all DJ paired notifications also show up as HID++ 1.0 notifications? if logger.isEnabledFor(logging.INFO): logger.info("%s: ignoring DJ unpaired: %s", device, n) return True if n.sub_id == Notification.DJ_PAIRING: # do all DJ paired notifications also show up as HID++ 1.0 notifications? if logger.isEnabledFor(logging.INFO): logger.info("%s: ignoring DJ paired: %s", device, n) return True if n.sub_id == Notification.CONNECTED: connected = not n.address & 0x01 if logger.isEnabledFor(logging.INFO): logger.info("%s: DJ connection: %s %s", device, connected, n) device.changed(active=connected, alert=Alert.NONE, reason=_("connected") if connected else _("disconnected")) return True logger.warning("%s: unrecognized DJ %s", device, n) def _process_hidpp10_custom_notification(device, n): if logger.isEnabledFor(logging.DEBUG): logger.debug("%s (%s) custom notification %s", device, device.protocol, n) if n.sub_id in (Registers.BATTERY_STATUS, Registers.BATTERY_CHARGE): assert n.data[-1:] == b"\x00" data = chr(n.address).encode() + n.data device.set_battery_info(hidpp10.parse_battery_status(n.sub_id, data)) return True logger.warning("%s: unrecognized %s", device, n) def _process_hidpp10_notification(device, n): if n.sub_id == Notification.CONNECT_DISCONNECT: # device unpairing if n.address == 0x02: # device un-paired device.wpid = None if device.number in device.receiver: del device.receiver[device.number] device.changed(active=False, alert=Alert.ALL, reason=_("unpaired")) ## device.status = None else: logger.warning("%s: disconnection with unknown type %02X: %s", device, n.address, n) return True if n.sub_id == Notification.DJ_PAIRING: # device connection (and disconnection) flags = ord(n.data[:1]) & 0xF0 if n.address == 0x02: # very old 27 MHz protocol wpid = "00" + common.strhex(n.data[2:3]) link_established = True link_encrypted = bool(flags & 0x80) elif n.address > 0x00: # all other protocols are supposed to be almost the same wpid = common.strhex(n.data[2:3] + n.data[1:2]) link_established = not (flags & 0x40) link_encrypted = bool(flags & 0x20) or n.address == 0x10 # Bolt protocol always encrypted else: logger.warning("%s: connection notification with unknown protocol %02X: %s", device.number, n.address, n) return True if wpid != device.wpid: logger.warning("%s wpid mismatch, got %s", device, wpid) if logger.isEnabledFor(logging.DEBUG): logger.debug( "%s: protocol %s connection notification: software=%s, encrypted=%s, link=%s, payload=%s", device, n.address, bool(flags & 0x10), link_encrypted, link_established, bool(flags & 0x80), ) device.link_encrypted = link_encrypted if not link_established and device.receiver: hidpp10.set_configuration_pending_flags(device.receiver, 0xFF) device.changed(active=link_established) return True if n.sub_id == Notification.RAW_INPUT: # raw input event? just ignore it # if n.address == 0x01, no idea what it is, but they keep on coming # if n.address == 0x03, appears to be an actual input event, because they only come when input happents return True if n.sub_id == Notification.POWER: if n.address == 0x01: if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: device powered on", device) reason = device.status_string() or _("powered on") device.changed(active=True, alert=Alert.NOTIFICATION, reason=reason) else: logger.warning("%s: unknown %s", device, n) return True logger.warning("%s: unrecognized %s", device, n) def _process_feature_notification(device, n, feature): if logger.isEnabledFor(logging.DEBUG): logger.debug( "%s: notification for feature %s, report %s, data %s", device, feature, n.address >> 4, common.strhex(n.data) ) if feature == _F.BATTERY_STATUS: if n.address == 0x00: device.set_battery_info(hidpp20.decipher_battery_status(n.data)[1]) elif n.address == 0x10: if logger.isEnabledFor(logging.INFO): logger.info("%s: spurious BATTERY status %s", device, n) else: logger.warning("%s: unknown BATTERY %s", device, n) elif feature == _F.BATTERY_VOLTAGE: if n.address == 0x00: device.set_battery_info(hidpp20.decipher_battery_voltage(n.data)[1]) else: logger.warning("%s: unknown VOLTAGE %s", device, n) elif feature == _F.UNIFIED_BATTERY: if n.address == 0x00: device.set_battery_info(hidpp20.decipher_battery_unified(n.data)[1]) else: logger.warning("%s: unknown UNIFIED BATTERY %s", device, n) elif feature == _F.ADC_MEASUREMENT: if n.address == 0x00: result = hidpp20.decipher_adc_measurement(n.data) if result: device.set_battery_info(result[1]) else: # this feature is used to signal device becoming inactive device.changed(active=False) else: logger.warning("%s: unknown ADC MEASUREMENT %s", device, n) elif feature == _F.SOLAR_DASHBOARD: if n.data[5:9] == b"GOOD": charge, lux, adc = struct.unpack("!BHH", n.data[:5]) # guesstimate the battery voltage, emphasis on 'guess' # status_text = '%1.2fV' % (adc * 2.67793237653 / 0x0672) status_text = BatteryStatus.DISCHARGING if n.address == 0x00: device.set_battery_info(common.Battery(charge, None, status_text, None)) elif n.address == 0x10: if lux > 200: status_text = BatteryStatus.RECHARGING device.set_battery_info(common.Battery(charge, None, status_text, None, lux)) elif n.address == 0x20: if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: Light Check button pressed", device) device.changed(alert=Alert.SHOW_WINDOW) # first cancel any reporting # device.feature_request(_F.SOLAR_DASHBOARD) # trigger a new report chain reports_count = 15 reports_period = 2 # seconds device.feature_request(_F.SOLAR_DASHBOARD, 0x00, reports_count, reports_period) else: logger.warning("%s: unknown SOLAR CHARGE %s", device, n) else: logger.warning("%s: SOLAR CHARGE not GOOD? %s", device, n) elif feature == _F.WIRELESS_DEVICE_STATUS: if n.address == 0x00: if logger.isEnabledFor(logging.DEBUG): logger.debug("wireless status: %s", n) reason = "powered on" if n.data[2] == 1 else None if n.data[1] == 1: # device is asking for software reconfiguration so need to change status alert = Alert.NONE device.changed(active=True, alert=alert, reason=reason, push=True) else: logger.warning("%s: unknown WIRELESS %s", device, n) elif feature == _F.TOUCHMOUSE_RAW_POINTS: if n.address == 0x00: if logger.isEnabledFor(logging.INFO): logger.info("%s: TOUCH MOUSE points %s", device, n) elif n.address == 0x10: touch = ord(n.data[:1]) button_down = bool(touch & 0x02) mouse_lifted = bool(touch & 0x01) if logger.isEnabledFor(logging.INFO): logger.info("%s: TOUCH MOUSE status: button_down=%s mouse_lifted=%s", device, button_down, mouse_lifted) else: logger.warning("%s: unknown TOUCH MOUSE %s", device, n) # TODO: what are REPROG_CONTROLS_V{2,3}? elif feature == _F.REPROG_CONTROLS: if n.address == 0x00: if logger.isEnabledFor(logging.INFO): logger.info("%s: reprogrammable key: %s", device, n) else: logger.warning("%s: unknown REPROG_CONTROLS %s", device, n) elif feature == _F.BACKLIGHT2: if n.address == 0x00: level = struct.unpack("!B", n.data[1:2])[0] if device.setting_callback: device.setting_callback(device, settings_templates.Backlight2Level, [level]) elif feature == _F.REPROG_CONTROLS_V4: if n.address == 0x00: if logger.isEnabledFor(logging.DEBUG): cid1, cid2, cid3, cid4 = struct.unpack("!HHHH", n.data[:8]) logger.debug("%s: diverted controls pressed: 0x%x, 0x%x, 0x%x, 0x%x", device, cid1, cid2, cid3, cid4) elif n.address == 0x10: if logger.isEnabledFor(logging.DEBUG): dx, dy = struct.unpack("!hh", n.data[:4]) logger.debug("%s: rawXY dx=%i dy=%i", device, dx, dy) elif n.address == 0x20: if logger.isEnabledFor(logging.DEBUG): logger.debug("%s: received analyticsKeyEvents", device) elif logger.isEnabledFor(logging.INFO): logger.info("%s: unknown REPROG_CONTROLS_V4 %s", device, n) elif feature == _F.HIRES_WHEEL: if n.address == 0x00: if logger.isEnabledFor(logging.INFO): flags, delta_v = struct.unpack(">bh", n.data[:3]) high_res = (flags & 0x10) != 0 periods = flags & 0x0F logger.info("%s: WHEEL: res: %d periods: %d delta V:%-3d", device, high_res, periods, delta_v) elif n.address == 0x10: ratchet = n.data[0] if logger.isEnabledFor(logging.INFO): logger.info("%s: WHEEL: ratchet: %d", device, ratchet) if ratchet < 2: # don't process messages with unusual ratchet values if device.setting_callback: device.setting_callback(device, settings_templates.ScrollRatchet, [2 if ratchet else 1]) else: if logger.isEnabledFor(logging.INFO): logger.info("%s: unknown WHEEL %s", device, n) elif feature == _F.ONBOARD_PROFILES: if n.address > 0x10: if logger.isEnabledFor(logging.INFO): logger.info("%s: unknown ONBOARD PROFILES %s", device, n) else: if n.address == 0x00: profile_sector = struct.unpack("!H", n.data[:2])[0] if profile_sector: settings_templates.profile_change(device, profile_sector) elif n.address == 0x10: resolution_index = struct.unpack("!B", n.data[:1])[0] profile_sector = struct.unpack("!H", device.feature_request(_F.ONBOARD_PROFILES, 0x40)[:2])[0] if device.setting_callback: for profile in device.profiles.profiles.values() if device.profiles else []: if profile.sector == profile_sector: device.setting_callback( device, settings_templates.AdjustableDpi, [profile.resolutions[resolution_index]] ) break elif feature == _F.BRIGHTNESS_CONTROL: if n.address > 0x10: if logger.isEnabledFor(logging.INFO): logger.info("%s: unknown BRIGHTNESS CONTROL %s", device, n) else: if n.address == 0x00: brightness = struct.unpack("!H", n.data[:2])[0] device.setting_callback(device, settings_templates.BrightnessControl, [brightness]) elif n.address == 0x10: brightness = n.data[0] & 0x01 if brightness: brightness = struct.unpack("!H", device.feature_request(_F.BRIGHTNESS_CONTROL, 0x10)[:2])[0] device.setting_callback(device, settings_templates.BrightnessControl, [brightness]) diversion.process_notification(device, n, feature) return True
21,624
Python
.py
420
40.961905
122
0.630369
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,472
common.py
pwr-Solaar_Solaar/lib/logitech_receiver/common.py
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/ ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from __future__ import annotations import binascii import dataclasses import typing from enum import IntEnum from typing import Generator from typing import Iterable from typing import Optional from typing import Union import yaml from solaar.i18n import _ if typing.TYPE_CHECKING: from logitech_receiver.hidpp20_constants import FirmwareKind LOGITECH_VENDOR_ID = 0x046D def crc16(data: bytes): """ CRC-16 (CCITT) implemented with a precomputed lookup table """ table = [ 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, 0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, 0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485, 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, 0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4, 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, 0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B, 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A, 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49, 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3, 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0, ] crc = 0xFFFF for byte in data: crc = (crc << 8) ^ table[(crc >> 8) ^ byte] crc &= 0xFFFF # important, crc must stay 16bits all the way through return crc class NamedInt(int): """A regular Python integer with an attached name. Caution: comparison with strings will also match this NamedInt's name (case-insensitive).""" def __new__(cls, value, name): assert isinstance(name, str) obj = int.__new__(cls, value) obj.name = str(name) return obj def bytes(self, count=2): return int2bytes(self, count) def __eq__(self, other): if other is None: return False if isinstance(other, NamedInt): return int(self) == int(other) and self.name == other.name if isinstance(other, int): return int(self) == int(other) if isinstance(other, str): return self.name.lower() == other.lower() # this should catch comparisons with bytes in Py3 if other is not None: raise TypeError("Unsupported type " + str(type(other))) def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return int(self) def __str__(self): return self.name def __repr__(self): return f"NamedInt({int(self)}, {self.name!r})" @classmethod def from_yaml(cls, loader, node): args = loader.construct_mapping(node) return cls(value=args["value"], name=args["name"]) @classmethod def to_yaml(cls, dumper, data): return dumper.represent_mapping("!NamedInt", {"value": int(data), "name": data.name}, flow_style=True) yaml.SafeLoader.add_constructor("!NamedInt", NamedInt.from_yaml) yaml.add_representer(NamedInt, NamedInt.to_yaml) class NamedInts: """An ordered set of NamedInt values. Indexing can be made by int or string, and will return the corresponding NamedInt if it exists in this set, or `None`. Extracting slices will return all present NamedInts in the given interval (extended slices are not supported). Assigning a string to an indexed int will create a new NamedInt in this set; if the value already exists in the set (int or string), ValueError will be raised. """ __slots__ = ("__dict__", "_values", "_indexed", "_fallback", "_is_sorted") def __init__(self, dict_=None, **kwargs): def _readable_name(n): return n.replace("__", "/").replace("_", " ") # print (repr(kwargs)) elements = dict_ if dict_ else kwargs values = {k: NamedInt(v, _readable_name(k)) for (k, v) in elements.items()} self.__dict__ = values self._is_sorted = False self._values = list(values.values()) self._sort_values() self._indexed = {int(v): v for v in self._values} # assert len(values) == len(self._indexed) # "(%d) %r\n=> (%d) %r" % (len(values), values, len(self._indexed), self._indexed) self._fallback = None @classmethod def list(cls, items, name_generator=lambda x: str(x)): # noqa: B008 values = {name_generator(x): x for x in items} return NamedInts(**values) @classmethod def range(cls, from_value, to_value, name_generator=lambda x: str(x), step=1): # noqa: B008 values = {name_generator(x): x for x in range(from_value, to_value + 1, step)} return NamedInts(**values) def flag_names(self, value): unknown_bits = value for k in self._indexed: assert bin(k).count("1") == 1 if k & value == k: unknown_bits &= ~k yield str(self._indexed[k]) if unknown_bits: yield f"unknown:{unknown_bits:06X}" def _sort_values(self): self._values = sorted(self._values) self._is_sorted = True def __getitem__(self, index): if isinstance(index, int): if index in self._indexed: return self._indexed[int(index)] if self._fallback: value = NamedInt(index, self._fallback(index)) self._indexed[index] = value self._values.append(value) self._is_sorted = False self._sort_values() return value elif isinstance(index, str): if index in self.__dict__: return self.__dict__[index] return next((x for x in self._values if str(x) == index), None) elif isinstance(index, slice): values = self._values if self._is_sorted else sorted(self._values) if index.start is None and index.stop is None: return values[:] v_start = int(values[0]) if index.start is None else int(index.start) v_stop = (values[-1] + 1) if index.stop is None else int(index.stop) if v_start > v_stop or v_start > values[-1] or v_stop <= values[0]: return [] if v_start <= values[0] and v_stop > values[-1]: return values[:] start_index = 0 stop_index = len(values) for i, value in enumerate(values): if value < v_start: start_index = i + 1 elif index.stop is None: break if value >= v_stop: stop_index = i break return values[start_index:stop_index] def __setitem__(self, index, name): assert isinstance(index, int), type(index) if isinstance(name, NamedInt): assert int(index) == int(name), repr(index) + " " + repr(name) value = name elif isinstance(name, str): value = NamedInt(index, name) else: raise TypeError("name must be a string") if str(value) in self.__dict__: raise ValueError(f"{value} ({int(value)}) already known") if int(value) in self._indexed: raise ValueError(f"{int(value)} ({value}) already known") self._values.append(value) self._is_sorted = False self._sort_values() self.__dict__[str(value)] = value self._indexed[int(value)] = value def __contains__(self, value): if isinstance(value, NamedInt): return self[value] == value elif isinstance(value, int): return value in self._indexed elif isinstance(value, str): return value in self.__dict__ or value in self._values def __iter__(self): yield from self._values def __len__(self): return len(self._values) def __repr__(self): return f"NamedInts({', '.join(repr(v) for v in self._values)})" def __or__(self, other): return NamedInts(**self.__dict__, **other.__dict__) def __eq__(self, other): return isinstance(other, self.__class__) and self._values == other._values def flag_names(enum_class: Iterable, value: int) -> Generator[str]: """Extracts single bit flags from a (binary) number. Parameters ---------- enum_class Enum class to extract flags from. value Number to extract binary flags from. """ indexed = {item.value: item.name for item in enum_class} unknown_bits = value for k in indexed: # Ensure that the key (flag value) is a power of 2 (a single bit flag) assert bin(k).count("1") == 1 if k & value == k: unknown_bits &= ~k yield indexed[k].lower() # Yield any remaining unknown bits if unknown_bits != 0: yield f"unknown:{unknown_bits:06X}" class UnsortedNamedInts(NamedInts): def _sort_values(self): pass def __or__(self, other): c = UnsortedNamedInts if isinstance(other, UnsortedNamedInts) else NamedInts return c(**self.__dict__, **other.__dict__) def strhex(x): assert x is not None """Produce a hex-string representation of a sequence of bytes.""" return binascii.hexlify(x).decode("ascii").upper() def bytes2int(x, signed=False): return int.from_bytes(x, signed=signed, byteorder="big") def int2bytes(x, count=None, signed=False): if count: return x.to_bytes(length=count, byteorder="big", signed=signed) else: return x.to_bytes(length=8, byteorder="big", signed=signed).lstrip(b"\x00") class KwException(Exception): """An exception that remembers all arguments passed to the constructor. They can be later accessed by simple member access. """ def __init__(self, **kwargs): super().__init__(kwargs) def __getattr__(self, k): try: return super().__getattr__(k) except AttributeError: return self.args[0].get(k) # was self.args[0][k] class FirmwareKind(IntEnum): Firmware = 0x00 Bootloader = 0x01 Hardware = 0x02 Other = 0x03 @dataclasses.dataclass class FirmwareInfo: kind: FirmwareKind name: str version: str extras: str | None class BatteryStatus(IntEnum): DISCHARGING = 0x00 RECHARGING = 0x01 ALMOST_FULL = 0x02 FULL = 0x03 SLOW_RECHARGE = 0x04 INVALID_BATTERY = 0x05 THERMAL_ERROR = 0x06 class BatteryLevelApproximation(IntEnum): EMPTY = 0 CRITICAL = 5 LOW = 20 GOOD = 50 FULL = 90 @dataclasses.dataclass class Battery: """Information about the current state of a battery""" ATTENTION_LEVEL = 5 level: Optional[Union[BatteryLevelApproximation, int]] next_level: Optional[Union[NamedInt, int]] status: Optional[BatteryStatus] voltage: Optional[int] light_level: Optional[int] = None # light level for devices with solaar recharging def __post_init__(self): if self.level is None: # infer level from status if needed and possible if self.status == BatteryStatus.FULL: self.level = BatteryLevelApproximation.FULL elif self.status in (BatteryStatus.ALMOST_FULL, BatteryStatus.RECHARGING): self.level = BatteryLevelApproximation.GOOD elif self.status == BatteryStatus.SLOW_RECHARGE: self.level = BatteryLevelApproximation.LOW def ok(self) -> bool: return self.status not in (BatteryStatus.INVALID_BATTERY, BatteryStatus.THERMAL_ERROR) and ( self.level is None or self.level > Battery.ATTENTION_LEVEL ) def charging(self) -> bool: return self.status in ( BatteryStatus.RECHARGING, BatteryStatus.ALMOST_FULL, BatteryStatus.FULL, BatteryStatus.SLOW_RECHARGE, ) def to_str(self) -> str: if isinstance(self.level, BatteryLevelApproximation): level = self.level.name.lower() status = self.status.name.lower().replace("_", " ") if self.status is not None else "Unknown" return _("Battery: %(level)s (%(status)s)") % {"level": _(level), "status": _(status)} elif isinstance(self.level, int): status = self.status.name.lower().replace("_", " ") if self.status is not None else "Unknown" return _("Battery: %(percent)d%% (%(status)s)") % {"percent": self.level, "status": _(status)} else: return "" class Alert(IntEnum): NONE = 0x00 NOTIFICATION = 0x01 SHOW_WINDOW = 0x02 ATTENTION = 0x04 ALL = 0xFF class Notification(IntEnum): NO_OPERATION = 0x00 CONNECT_DISCONNECT = 0x40 DJ_PAIRING = 0x41 CONNECTED = 0x42 RAW_INPUT = 0x49 PAIRING_LOCK = 0x4A POWER = 0x4B class BusID(IntEnum): USB = 0x03 BLUETOOTH = 0x05
17,148
Python
.py
581
21.156627
110
0.568844
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,473
configuration.py
pwr-Solaar_Solaar/lib/solaar/configuration.py
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/ ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import json import logging import os import threading import yaml from logitech_receiver.common import NamedInt from solaar import __version__ logger = logging.getLogger(__name__) _XDG_CONFIG_HOME = os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser(os.path.join("~", ".config")) _yaml_file_path = os.path.join(_XDG_CONFIG_HOME, "solaar", "config.yaml") _json_file_path = os.path.join(_XDG_CONFIG_HOME, "solaar", "config.json") _KEY_VERSION = "_version" _KEY_NAME = "_NAME" _KEY_WPID = "_wpid" _KEY_SERIAL = "_serial" _KEY_MODEL_ID = "_modelId" _KEY_UNIT_ID = "_unitId" _KEY_ABSENT = "_absent" _KEY_SENSITIVE = "_sensitive" _config = [] def _load(): loaded_config = [] if os.path.isfile(_yaml_file_path): path = _yaml_file_path try: with open(_yaml_file_path) as config_file: loaded_config = yaml.safe_load(config_file) except Exception as e: logger.error("failed to load from %s: %s", _yaml_file_path, e) elif os.path.isfile(_json_file_path): path = _json_file_path try: with open(_json_file_path) as config_file: loaded_config = json.load(config_file) except Exception as e: logger.error("failed to load from %s: %s", _json_file_path, e) loaded_config = _convert_json(loaded_config) else: path = None if logger.isEnabledFor(logging.DEBUG): logger.debug("load => %s", loaded_config) global _config _config = _parse_config(loaded_config, path) def _parse_config(loaded_config, config_path): current_version = __version__ parsed_config = [current_version] try: if not loaded_config: return parsed_config loaded_version = loaded_config[0] discard_derived_properties = loaded_version != current_version if discard_derived_properties: if logger.isEnabledFor(logging.INFO): logger.info( "config file '%s' was generated by another version of solaar " "(config: %s, current: %s). refreshing detected device capabilities", config_path, loaded_version, current_version, ) for device in loaded_config[1:]: assert isinstance(device, dict) parsed_config.append(_device_entry_from_config_dict(device, discard_derived_properties)) except Exception as e: logger.warning("Exception processing config file '%s', ignoring contents: %s", config_path, e) return parsed_config def _device_entry_from_config_dict(data, discard_derived_properties): divert = data.get("divert-keys") if divert: sliding = data.get("dpi-sliding") if sliding: # convert old-style dpi-sliding setting to divert-keys entry divert[int(sliding)] = 3 data.pop("dpi-sliding", None) gestures = data.get("mouse-gestures") if gestures: # convert old-style mouse-gestures setting to divert-keys entry divert[int(gestures)] = 2 data.pop("mouse-gestures", None) # remove any string entries (from bad conversions) data["divert-keys"] = {k: v for k, v in divert.items() if isinstance(k, int)} if data.get("_sensitive", None) is None: # make scroll wheel settings default to ignore data["_sensitive"] = { "hires-smooth-resolution": "ignore", "hires-smooth-invert": "ignore", "hires-scroll-mode": "ignore", } if discard_derived_properties: data.pop("_absent", None) data.pop("_battery", None) return _DeviceEntry(**data) save_timer = None configuration_lock = threading.Lock() defer_saves = False # don't allow configuration saves to be deferred def save(defer=False): global save_timer if not _config: return dirname = os.path.dirname(_yaml_file_path) if not os.path.isdir(dirname): try: os.makedirs(dirname) except Exception: logger.error("failed to create %s", dirname) return if not defer or not defer_saves: do_save() else: with configuration_lock: if not save_timer: save_timer = threading.Timer(5.0, do_save) save_timer.start() def do_save(): global save_timer with configuration_lock: if save_timer: save_timer.cancel() save_timer = None try: with open(_yaml_file_path, "w") as config_file: yaml.dump(_config, config_file, default_flow_style=None, width=150) if logger.isEnabledFor(logging.INFO): logger.info("saved %s to %s", _config, _yaml_file_path) except Exception as e: logger.error("failed to save to %s: %s", _yaml_file_path, e) def _convert_json(json_dict): config = [json_dict.get(_KEY_VERSION)] for key, dev in json_dict.items(): key = key.split(":") if len(key) == 2: dev[_KEY_WPID] = dev.get(_KEY_WPID) if dev.get(_KEY_WPID) else key[0] dev[_KEY_SERIAL] = dev.get(_KEY_SERIAL) if dev.get(_KEY_SERIAL) else key[1] for k, v in dev.items(): if isinstance(k, str) and not k.startswith("_") and isinstance(v, dict): # convert string keys to ints v = {int(dk) if isinstance(dk, str) else dk: dv for dk, dv in v.items()} dev[k] = v for k in ["mouse-gestures", "dpi-sliding"]: v = dev.get(k, None) if v is True or v is False: dev.pop(k) if "_name" in dev: dev[_KEY_NAME] = dev["_name"] dev.pop("_name") config.append(dev) return config class _DeviceEntry(dict): def __init__(self, **kwargs): super().__init__(**kwargs) def __setitem__(self, key, value): super().__setitem__(key, value) save(defer=True) def update(self, name, wpid, serial, modelId, unitId): if name and name != self.get(_KEY_NAME): super().__setitem__(_KEY_NAME, name) if wpid and wpid != self.get(_KEY_WPID): super().__setitem__(_KEY_WPID, wpid) if serial and serial != self.get(_KEY_SERIAL): super().__setitem__(_KEY_SERIAL, serial) if modelId and modelId != self.get(_KEY_MODEL_ID): super().__setitem__(_KEY_MODEL_ID, modelId) if unitId and unitId != self.get(_KEY_UNIT_ID): super().__setitem__(_KEY_UNIT_ID, unitId) def get_sensitivity(self, name): return self.get(_KEY_SENSITIVE, {}).get(name, False) def set_sensitivity(self, name, value): sensitives = self.get(_KEY_SENSITIVE, {}) if sensitives.get(name) != value: sensitives[name] = value self.__setitem__(_KEY_SENSITIVE, sensitives) def device_representer(dumper, data): return dumper.represent_mapping("tag:yaml.org,2002:map", data) yaml.add_representer(_DeviceEntry, device_representer) def named_int_representer(dumper, data): return dumper.represent_scalar("tag:yaml.org,2002:int", str(int(data))) yaml.add_representer(NamedInt, named_int_representer) # A device can be identified by a combination of WPID and serial number (for receiver-connected devices) # or a combination of modelId and unitId (for direct-connected devices). # But some devices have empty (all zero) modelIds and unitIds. Use the device name as a backup for the modelId. # The worst situation is a receiver-connected device that Solaar has never seen on-line # that is directly connected. Here there is no way to realize that the two devices are the same. # So new entries are not created for unseen off-line receiver-connected devices def persister(device): def match(wpid, serial, modelId, unitId, c): return (wpid and wpid == c.get(_KEY_WPID) and serial and serial == c.get(_KEY_SERIAL)) or ( modelId and modelId == c.get(_KEY_MODEL_ID) and unitId and unitId == c.get(_KEY_UNIT_ID) ) with configuration_lock: if not _config: _load() entry = None # some devices report modelId and unitId as zero so use name and serial for them modelId = device.modelId if device.modelId != "000000000000" else device._name if device.modelId else None unitId = device.unitId if device.modelId != "000000000000" else device._serial if device.unitId else None for c in _config: if isinstance(c, _DeviceEntry) and match(device.wpid, device._serial, modelId, unitId, c): entry = c break if not entry: if not device.online: # don't create entry for offline devices if logger.isEnabledFor(logging.INFO): logger.info("not setting up persister for offline device %s", device._name) return if logger.isEnabledFor(logging.INFO): logger.info("setting up persister for device %s", device.name) entry = _DeviceEntry() _config.append(entry) entry.update(device.name, device.wpid, device.serial, modelId, unitId) return entry def attach_to(device): pass
10,171
Python
.py
224
37.111607
119
0.631297
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,474
dbus.py
pwr-Solaar_Solaar/lib/solaar/dbus.py
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/ ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from __future__ import annotations import logging from typing import Callable logger = logging.getLogger(__name__) try: import dbus from dbus.mainloop.glib import DBusGMainLoop # integration into the main GLib loop DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() assert bus except Exception: # Either the dbus library is not available or the system dbus is not running logger.warning("failed to set up dbus") bus = None _suspend_callback = None _resume_callback = None def _suspend_or_resume(suspend): if suspend and _suspend_callback: _suspend_callback() if not suspend and _resume_callback: _resume_callback() _LOGIND_PATH = "/org/freedesktop/login1" _LOGIND_INTERFACE = "org.freedesktop.login1.Manager" def watch_suspend_resume( on_resume_callback: Callable[[], None] | None = None, on_suspend_callback: Callable[[], None] | None = None, ): """Register callback for suspend/resume events. They are called only if the system DBus is running, and the Login daemon is available.""" global _resume_callback, _suspend_callback _suspend_callback = on_suspend_callback _resume_callback = on_resume_callback if bus is not None and on_resume_callback is not None or on_suspend_callback is not None: bus.add_signal_receiver( _suspend_or_resume, "PrepareForSleep", dbus_interface=_LOGIND_INTERFACE, path=_LOGIND_PATH, ) if logger.isEnabledFor(logging.INFO): logger.info("connected to system dbus, watching for suspend/resume events") _BLUETOOTH_PATH_PREFIX = "/org/bluez/hci0/dev_" _BLUETOOTH_INTERFACE = "org.freedesktop.DBus.Properties" _bluetooth_callbacks = {} def watch_bluez_connect(serial, callback=None): if _bluetooth_callbacks.get(serial): _bluetooth_callbacks.get(serial).remove() path = _BLUETOOTH_PATH_PREFIX + serial.replace(":", "_").upper() if bus is not None and callback is not None: _bluetooth_callbacks[serial] = bus.add_signal_receiver( callback, "PropertiesChanged", path=path, dbus_interface=_BLUETOOTH_INTERFACE )
3,019
Python
.py
68
39.985294
93
0.725691
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,475
listener.py
pwr-Solaar_Solaar/lib/solaar/listener.py
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/ ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import errno import logging import subprocess import time from collections import namedtuple from functools import partial import gi import logitech_receiver from logitech_receiver import base from logitech_receiver import exceptions from logitech_receiver import hidpp10_constants from logitech_receiver import listener from logitech_receiver import notifications from . import configuration from . import dbus from . import i18n gi.require_version("Gtk", "3.0") # NOQA: E402 from gi.repository import GLib # NOQA: E402 # isort:skip logger = logging.getLogger(__name__) ACTION_ADD = "add" _GHOST_DEVICE = namedtuple("_GHOST_DEVICE", ("receiver", "number", "name", "kind", "online")) _GHOST_DEVICE.__bool__ = lambda self: False _GHOST_DEVICE.__nonzero__ = _GHOST_DEVICE.__bool__ def _ghost(device): return _GHOST_DEVICE( receiver=device.receiver, number=device.number, name=device.name, kind=device.kind, online=False, ) class SolaarListener(listener.EventsListener): """Keeps the status of a Receiver or Device (member name is receiver but it can also be a device).""" def __init__(self, receiver, status_changed_callback): assert status_changed_callback super().__init__(receiver, self._notifications_handler) self.status_changed_callback = status_changed_callback receiver.status_callback = self._status_changed def has_started(self): if logger.isEnabledFor(logging.INFO): logger.info("%s: notifications listener has started (%s)", self.receiver, self.receiver.handle) nfs = self.receiver.enable_connection_notifications() if logger.isEnabledFor(logging.WARNING): if not self.receiver.isDevice and not ((nfs if nfs else 0) & hidpp10_constants.NOTIFICATION_FLAG.wireless): logger.warning( "Receiver on %s might not support connection notifications, GUI might not show its devices", self.receiver.path, ) self.receiver.notification_flags = nfs self.receiver.notify_devices() self._status_changed(self.receiver) def has_stopped(self): r, self.receiver = self.receiver, None assert r is not None if logger.isEnabledFor(logging.INFO): logger.info("%s: notifications listener has stopped", r) # because udev is not notifying us about device removal, make sure to clean up in _all_listeners _all_listeners.pop(r.path, None) # this causes problems but what is it doing (pfps) - r.status = _('The receiver was unplugged.') if r: try: r.close() except Exception: logger.exception(f"closing receiver {r.path}") self.status_changed_callback(r) def _status_changed(self, device, alert=None, reason=None): assert device is not None if logger.isEnabledFor(logging.INFO): try: if device.kind is None: logger.info( "status_changed %r: %s (%X) %s", device, "present" if bool(device) else "removed", alert if alert is not None else 0, reason or "", ) else: device.ping() logger.info( "status_changed %r: %s %s (%X) %s", device, "paired" if bool(device) else "unpaired", "online" if device.online else "offline", alert if alert is not None else 0, reason or "", ) except Exception as e: logger.info("status_changed for unknown device: %s", e) if device.kind is None: assert device == self.receiver # the status of the receiver changed self.status_changed_callback(device, alert, reason) return # not true for wired devices - assert device.receiver == self.receiver if not device: # Device was unpaired, and isn't valid anymore. # We replace it with a ghost so that the UI has something to work with while cleaning up. if logger.isEnabledFor(logging.INFO): logger.info("device %s was unpaired, ghosting", device) device = _ghost(device) self.status_changed_callback(device, alert, reason) if not device: # the device was just unpaired, need to update the status of the receiver as well self.status_changed_callback(self.receiver) def _notifications_handler(self, n): assert self.receiver if n.devnumber == 0xFF: # a receiver notification notifications.process(self.receiver, n) return # a notification that came in to the device listener - strange, but nothing needs to be done here if self.receiver.isDevice: if logger.isEnabledFor(logging.DEBUG): logger.debug("Notification %s via device %s being ignored.", n, self.receiver) return # DJ pairing notification - ignore - hid++ 1.0 pairing notification is all that is needed if n.sub_id == 0x41 and n.report_id == base.DJ_MESSAGE_ID: if logger.isEnabledFor(logging.INFO): logger.info("ignoring DJ pairing notification %s", n) return # a device notification if not (0 < n.devnumber <= 16): # some receivers have devices past their max # devices if logger.isEnabledFor(logging.WARNING): logger.warning("Unexpected device number (%s) in notification %s.", n.devnumber, n) return already_known = n.devnumber in self.receiver # FIXME: hacky fix for kernel/hardware race condition # If the device was just turned on or woken up from sleep, it may not be ready to receive commands. # The "payload" bit of the wireless status notification seems to tell us this. If this is the case, we # must wait a short amount of time to avoid causing a broken pipe error. device_ready = not bool(ord(n.data[0:1]) & 0x80) or n.sub_id != 0x41 if not device_ready: time.sleep(0.01) if n.sub_id == 0x40 and not already_known: return # disconnecting something that is not known - nothing to do if n.sub_id == 0x41: if not already_known: if n.address == 0x0A and not self.receiver.receiver_kind == "bolt": # some Nanos send a notification even if no new pairing - check that there really is a device there if ( self.receiver.read_register( hidpp10_constants.Registers.RECEIVER_INFO, hidpp10_constants.INFO_SUBREGISTERS.pairing_information + n.devnumber - 1, ) is None ): return dev = self.receiver.register_new_device(n.devnumber, n) elif self.receiver.pairing.lock_open and self.receiver.re_pairs and not ord(n.data[0:1]) & 0x40: dev = self.receiver[n.devnumber] del self.receiver[n.devnumber] # get rid of information on device re-paired away self._status_changed(dev) # signal that this device has changed dev = self.receiver.register_new_device(n.devnumber, n) self.receiver.pairing.new_device = self.receiver[n.devnumber] else: dev = self.receiver[n.devnumber] else: dev = self.receiver[n.devnumber] if not dev: logger.warning("%s: received %s for invalid device %d: %r", self.receiver, n, n.devnumber, dev) return # Apply settings every time the device connects if n.sub_id == 0x41: if logger.isEnabledFor(logging.INFO): logger.info("connection %s for device wpid %s kind %s serial %s", n, dev.wpid, dev.kind, dev._serial) # If there are saved configs, bring the device's settings up-to-date. # They will be applied when the device is marked as online. configuration.attach_to(dev) dev.status_callback = self._status_changed # the receiver changed status as well self._status_changed(self.receiver) notifications.process(dev, n) if self.receiver.pairing.lock_open and not already_known: # this should be the first notification after a device was paired if logger.isEnabledFor(logging.WARNING): logger.warning("first notification was not a connection notification") if logger.isEnabledFor(logging.INFO): logger.info("%s: pairing detected new device", self.receiver) self.receiver.pairing.new_device = dev elif dev.online is None: dev.ping() def __str__(self): return f"<SolaarListener({self.receiver.path},{self.receiver.handle})>" def _process_bluez_dbus(device, path, dictionary, signature): """Process bluez dbus property changed signals for device status changes to discover disconnections and connections. """ if device: if dictionary.get("Connected") is not None: connected = dictionary.get("Connected") if logger.isEnabledFor(logging.INFO): logger.info("bluez dbus for %s: %s", device, "CONNECTED" if connected else "DISCONNECTED") device.changed(connected, reason=i18n._("connected") if connected else i18n._("disconnected")) elif device is not None: if logger.isEnabledFor(logging.INFO): logger.info("bluez cleanup for %s", device) _cleanup_bluez_dbus(device) def _cleanup_bluez_dbus(device): """Remove dbus signal receiver for device""" if logger.isEnabledFor(logging.INFO): logger.info("bluez cleanup for %s", device) dbus.watch_bluez_connect(device.hid_serial, None) _all_listeners = {} # all known receiver listeners, listeners that stop on their own may remain here def _start(device_info): assert _status_callback and _setting_callback isDevice = device_info.isDevice if not isDevice: receiver_ = logitech_receiver.receiver.create_receiver(base, device_info, _setting_callback) else: receiver_ = logitech_receiver.device.create_device(base, device_info, _setting_callback) if receiver_: configuration.attach_to(receiver_) if receiver_.bluetooth and receiver_.hid_serial: dbus.watch_bluez_connect(receiver_.hid_serial, partial(_process_bluez_dbus, receiver_)) receiver_.cleanups.append(_cleanup_bluez_dbus) if receiver_: rl = SolaarListener(receiver_, _status_callback) rl.start() _all_listeners[device_info.path] = rl return rl logger.warning("failed to open %s", device_info) def start_all(): stop_all() # just in case this it called twice in a row... if logger.isEnabledFor(logging.INFO): logger.info("starting receiver listening threads") for device_info in base.receivers_and_devices(): _process_receiver_event(ACTION_ADD, device_info) def stop_all(): listeners = list(_all_listeners.values()) _all_listeners.clear() if listeners: if logger.isEnabledFor(logging.INFO): logger.info("stopping receiver listening threads %s", listeners) for listener_thread in listeners: listener_thread.stop() configuration.save() if listeners: for listener_thread in listeners: listener_thread.join() # after a resume, the device may have been off so mark its saved status to ensure # that the status is pushed to the device when it comes back def ping_all(resuming=False): if logger.isEnabledFor(logging.INFO): logger.info("ping all devices%s", " when resuming" if resuming else "") for listener_thread in _all_listeners.values(): if listener_thread.receiver.isDevice: if resuming: listener_thread.receiver._active = None # ensure that settings are pushed if listener_thread.receiver.ping(): listener_thread.receiver.changed(active=True, push=True) listener_thread._status_changed(listener_thread.receiver) else: count = listener_thread.receiver.count() if count: for dev in listener_thread.receiver: if resuming: dev._active = None # ensure that settings are pushed if dev.ping(): dev.changed(active=True, push=True) listener_thread._status_changed(dev) count -= 1 if not count: break _status_callback = None # GUI callback to change UI in response to changes to receiver or device status _setting_callback = None # GUI callback to change UI in response to changes to status _error_callback = None # GUI callback to report errors def setup_scanner(status_changed_callback, setting_changed_callback, error_callback): global _status_callback, _error_callback, _setting_callback assert _status_callback is None, "scanner was already set-up" _status_callback = status_changed_callback _setting_callback = setting_changed_callback _error_callback = error_callback base.notify_on_receivers_glib(GLib, _process_receiver_event) def _process_add(device_info, retry): try: _start(device_info) except OSError as e: if e.errno == errno.EACCES: try: output = subprocess.check_output(["/usr/bin/getfacl", "-p", device_info.path], text=True) if logger.isEnabledFor(logging.WARNING): logger.warning("Missing permissions on %s\n%s.", device_info.path, output) except Exception: pass if retry: GLib.timeout_add(2000.0, _process_add, device_info, retry - 1) else: _error_callback("permissions", device_info.path) else: _error_callback("nodevice", device_info.path) except exceptions.NoReceiver: _error_callback("nodevice", device_info.path) # receiver add/remove events will start/stop listener threads def _process_receiver_event(action, device_info): assert action is not None assert device_info is not None assert _error_callback if logger.isEnabledFor(logging.INFO): logger.info("receiver event %s %s", action, device_info) # whatever the action, stop any previous receivers at this path listener_thread = _all_listeners.pop(device_info.path, None) if listener_thread is not None: assert isinstance(listener_thread, SolaarListener) listener_thread.stop() if action == ACTION_ADD: _process_add(device_info, 3) return False
16,114
Python
.py
324
39.367284
119
0.63734
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,476
tasks.py
pwr-Solaar_Solaar/lib/solaar/tasks.py
#!/usr/bin/env python3 ## Copyright (C) 2012-2013 Daniel Pavel ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import logging from threading import Thread logger = logging.getLogger(__name__) try: from Queue import Queue except ImportError: from queue import Queue class TaskRunner(Thread): def __init__(self, name): super().__init__(name=name) self.daemon = True self.queue = Queue(16) self.alive = False def __call__(self, function, *args, **kwargs): task = (function, args, kwargs) self.queue.put(task) def stop(self): self.alive = False self.queue.put(None) def run(self): self.alive = True if logger.isEnabledFor(logging.DEBUG): logger.debug("started") while self.alive: task = self.queue.get() if task: function, args, kwargs = task assert function try: function(*args, **kwargs) except Exception: logger.exception("calling %s", function) if logger.isEnabledFor(logging.DEBUG): logger.debug("stopped")
1,866
Python
.py
50
30.62
74
0.65391
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,477
i18n.py
pwr-Solaar_Solaar/lib/solaar/i18n.py
## Copyright (C) 2012-2013 Daniel Pavel ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import gettext import locale import os import sys from glob import glob from solaar import NAME _LOCALE_DOMAIN = NAME.lower() def _find_locale_path(locale_domain: str) -> str: prefix_share = os.path.normpath(os.path.join(os.path.realpath(sys.path[0]), "..")) src_share = os.path.normpath(os.path.join(os.path.realpath(sys.path[0]), "..", "share")) for location in prefix_share, src_share: mo_files = glob(os.path.join(location, "locale", "*", "LC_MESSAGES", locale_domain + ".mo")) if mo_files: return os.path.join(location, "locale") raise FileNotFoundError(f"Could not find locale path for {locale_domain}") def set_locale_to_system_default(): """Sets locale for translations to the system default. Set LC_ALL environment variable to enforce a locale setting e.g. 'de_DE.UTF-8'. Run Solaar with your desired localization, for German use: 'LC_ALL=de_DE.UTF-8 solaar' """ try: locale.setlocale(locale.LC_ALL, "") except PermissionError: pass try: path = _find_locale_path(_LOCALE_DOMAIN) except FileNotFoundError: path = None gettext.bindtextdomain(_LOCALE_DOMAIN, path) gettext.textdomain(_LOCALE_DOMAIN) gettext.install(_LOCALE_DOMAIN) set_locale_to_system_default() _ = gettext.gettext ngettext = gettext.ngettext
2,120
Python
.py
51
37.784314
100
0.721168
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,478
__init__.py
pwr-Solaar_Solaar/lib/solaar/__init__.py
## Copyright (C) 2012-2013 Daniel Pavel ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import pkgutil import subprocess import sys NAME = "Solaar" try: __version__ = ( subprocess.check_output( [ "git", "describe", "--always", ], cwd=sys.path[0], stderr=subprocess.DEVNULL, ) .strip() .decode() ) except Exception: try: __version__ = pkgutil.get_data("solaar", "commit").strip().decode() except Exception: __version__ = pkgutil.get_data("solaar", "version").strip().decode()
1,311
Python
.py
38
29.210526
76
0.65748
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,479
gtk.py
pwr-Solaar_Solaar/lib/solaar/gtk.py
#!/usr/bin/env python3 ## Copyright (C) 2012-2013 Daniel Pavel ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import argparse import faulthandler import importlib import locale import logging import os.path import platform import signal import sys import tempfile from traceback import format_exc from solaar import NAME from solaar import __version__ from solaar import cli from solaar import configuration from solaar import dbus from solaar import listener from solaar import ui logger = logging.getLogger(__name__) def _require(module, os_package, gi=None, gi_package=None, gi_version=None): try: if gi is not None: gi.require_version(gi_package, gi_version) return importlib.import_module(module) except (ImportError, ValueError): sys.exit(f"{NAME.lower()}: missing required system package {os_package}") battery_icons_style = "regular" tray_icon_size = None temp = tempfile.NamedTemporaryFile(prefix="Solaar_", mode="w", delete=True) def _parse_arguments(): arg_parser = argparse.ArgumentParser( prog=NAME.lower(), epilog="For more information see https://pwr-solaar.github.io/Solaar" ) arg_parser.add_argument( "-d", "--debug", action="count", default=0, help="print logging messages, for debugging purposes (may be repeated for extra verbosity)", ) arg_parser.add_argument( "-D", "--hidraw", action="store", dest="hidraw_path", metavar="PATH", help="unifying receiver to use; the first detected receiver if unspecified. Example: /dev/hidraw2", ) arg_parser.add_argument( "--restart-on-wake-up", action="store_true", help="restart Solaar on sleep wake-up (experimental)", ) arg_parser.add_argument( "-w", "--window", choices=("show", "hide", "only"), help="start with window showing / hidden / only (no tray icon)", ) arg_parser.add_argument( "-b", "--battery-icons", choices=("regular", "symbolic", "solaar"), help="prefer regular battery / symbolic battery / solaar icons", ) arg_parser.add_argument("--tray-icon-size", type=int, help="explicit size for tray icons") arg_parser.add_argument("-V", "--version", action="version", version="%(prog)s " + __version__) arg_parser.add_argument("--help-actions", action="store_true", help="describe the command-line actions") arg_parser.add_argument( "action", nargs=argparse.REMAINDER, choices=cli.actions, help="command-line action to perform (optional); append ' --help' to show args", ) args = arg_parser.parse_args() if args.help_actions: cli.print_help() return if args.window is None: args.window = "show" # default behaviour is to show main window global battery_icons_style battery_icons_style = args.battery_icons if args.battery_icons is not None else "regular" global tray_icon_size tray_icon_size = args.tray_icon_size log_format = "%(asctime)s,%(msecs)03d %(levelname)8s [%(threadName)s] %(name)s: %(message)s" log_level = logging.ERROR - 10 * args.debug logging.getLogger("").setLevel(min(log_level, logging.WARNING)) file_handler = logging.StreamHandler(temp) file_handler.setLevel(max(min(log_level, logging.WARNING), logging.INFO)) file_handler.setFormatter(logging.Formatter(log_format)) logging.getLogger("").addHandler(file_handler) if args.debug > 0: stream_handler = logging.StreamHandler() stream_handler.setFormatter(logging.Formatter(log_format)) stream_handler.setLevel(log_level) logging.getLogger("").addHandler(stream_handler) if not args.action: if logger.isEnabledFor(logging.INFO): language, encoding = locale.getlocale() logger.info("version %s, language %s (%s)", __version__, language, encoding) return args # On first SIGINT, dump threads to stderr; on second, exit def _handlesig(signl, stack): signal.signal(signal.SIGINT, signal.SIG_DFL) signal.signal(signal.SIGTERM, signal.SIG_DFL) if signl == int(signal.SIGINT): if logger.isEnabledFor(logging.INFO): faulthandler.dump_traceback() sys.exit(f"{NAME.lower()}: exit due to keyboard interrupt") else: sys.exit(0) def main(): if platform.system() not in ("Darwin", "Windows"): _require("pyudev", "python3-pyudev") args = _parse_arguments() if not args: return if args.action: # if any argument, run comandline and exit return cli.run(args.action, args.hidraw_path) gi = _require("gi", "python3-gi (in Ubuntu) or python3-gobject (in Fedora)") _require("gi.repository.Gtk", "gir1.2-gtk-3.0", gi, "Gtk", "3.0") # handle ^C in console signal.signal(signal.SIGINT, signal.SIG_DFL) signal.signal(signal.SIGINT, _handlesig) signal.signal(signal.SIGTERM, _handlesig) udev_file = "42-logitech-unify-permissions.rules" if ( logger.isEnabledFor(logging.WARNING) and not os.path.isfile("/etc/udev/rules.d/" + udev_file) and not os.path.isfile("/usr/lib/udev/rules.d/" + udev_file) and not os.path.isfile("/usr/local/lib/udev/rules.d/" + udev_file) ): logger.warning("Solaar udev file not found in expected location") logger.warning("See https://pwr-solaar.github.io/Solaar/installation for more information") try: listener.setup_scanner(ui.status_changed, ui.setting_changed, ui.common.error_dialog) if args.restart_on_wake_up: dbus.watch_suspend_resume(listener.start_all, listener.stop_all) else: dbus.watch_suspend_resume(lambda: listener.ping_all(True)) configuration.defer_saves = True # allow configuration saves to be deferred # main UI event loop ui.run_loop(listener.start_all, listener.stop_all, args.window != "only", args.window != "hide") except Exception: sys.exit(f"{NAME.lower()}: error: {format_exc()}") temp.close() if __name__ == "__main__": main()
6,868
Python
.py
165
35.793939
108
0.67946
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,480
window.py
pwr-Solaar_Solaar/lib/solaar/ui/window.py
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/ ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import logging import gi from gi.repository.GObject import TYPE_PYOBJECT from logitech_receiver import hidpp10_constants from logitech_receiver.common import LOGITECH_VENDOR_ID from logitech_receiver.common import NamedInt from logitech_receiver.common import NamedInts from solaar import NAME from solaar.i18n import _ from solaar.i18n import ngettext from . import action from . import config_panel from . import diversion_rules from . import icons from .about import about from .common import ui_async gi.require_version("Gdk", "3.0") from gi.repository import Gdk # NOQA: E402 from gi.repository import GLib # NOQA: E402 from gi.repository import Gtk # NOQA: E402 logger = logging.getLogger(__name__) _SMALL_BUTTON_ICON_SIZE = Gtk.IconSize.MENU _NORMAL_BUTTON_ICON_SIZE = Gtk.IconSize.BUTTON _TREE_ICON_SIZE = Gtk.IconSize.BUTTON _INFO_ICON_SIZE = Gtk.IconSize.LARGE_TOOLBAR _DEVICE_ICON_SIZE = Gtk.IconSize.DND try: gi.check_version("3.7.4") _CAN_SET_ROW_NONE = None except (ValueError, AttributeError): _CAN_SET_ROW_NONE = "" # tree model columns _COLUMN = NamedInts(PATH=0, NUMBER=1, ACTIVE=2, NAME=3, ICON=4, STATUS_TEXT=5, STATUS_ICON=6, DEVICE=7) _COLUMN_TYPES = (str, int, bool, str, str, str, str, TYPE_PYOBJECT) _TREE_SEPATATOR = (None, 0, False, None, None, None, None, None) assert len(_TREE_SEPATATOR) == len(_COLUMN_TYPES) assert len(_COLUMN_TYPES) == len(_COLUMN) def _new_button(label, icon_name=None, icon_size=_NORMAL_BUTTON_ICON_SIZE, tooltip=None, toggle=False, clicked=None): b = Gtk.ToggleButton() if toggle else Gtk.Button() c = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 5) if icon_name: c.pack_start(Gtk.Image.new_from_icon_name(icon_name, icon_size), True, True, 0) if label: c.pack_start(Gtk.Label(label=label), True, True, 0) b.add(c) if clicked is not None: b.connect("clicked", clicked) if tooltip: b.set_tooltip_text(tooltip) if not label and icon_size < _NORMAL_BUTTON_ICON_SIZE: b.set_relief(Gtk.ReliefStyle.NONE) b.set_focus_on_click(False) return b def _create_receiver_panel(): p = Gtk.Box.new(Gtk.Orientation.VERTICAL, 4) p._count = Gtk.Label() p._count.set_margin_top(24) p.pack_start(p._count, True, True, 0) p._scanning = Gtk.Label(label=_("Scanning") + "...") p._spinner = Gtk.Spinner() bp = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 8) bp.pack_start(Gtk.Label(label=" "), True, True, 0) bp.pack_start(p._scanning, False, False, 0) bp.pack_end(p._spinner, False, False, 0) p.pack_end(bp, False, False, 0) return p def _create_device_panel(): p = Gtk.Box.new(Gtk.Orientation.VERTICAL, 4) def _status_line(label_text): b = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 8) b.set_size_request(10, 28) b._label = Gtk.Label(label=label_text) b._label.set_size_request(170, 10) b.pack_start(b._label, False, False, 0) b._icon = Gtk.Image() b.pack_start(b._icon, False, False, 0) b._text = Gtk.Label() b.pack_start(b._text, False, False, 0) return b p._battery = _status_line(_("Battery")) p.pack_start(p._battery, False, False, 0) p._secure = _status_line(_("Wireless Link")) p._secure._icon.set_from_icon_name("dialog-warning", _INFO_ICON_SIZE) p.pack_start(p._secure, False, False, 0) p._lux = _status_line(_("Lighting")) p.pack_start(p._lux, False, False, 0) p.pack_start(Gtk.Separator.new(Gtk.Orientation.HORIZONTAL), False, False, 0) # spacer p._config = config_panel.create() p.pack_end(p._config, True, True, 4) return p def _create_details_panel(): p = Gtk.Frame() p.set_shadow_type(Gtk.ShadowType.NONE) p.set_size_request(240, 0) p.set_state_flags(Gtk.StateFlags.ACTIVE, True) p._text = Gtk.Label() p._text.set_margin_start(6) p._text.set_margin_end(4) p._text.set_selectable(True) p.add(p._text) return p def _create_buttons_box(): bb = Gtk.HButtonBox() bb.set_layout(Gtk.ButtonBoxStyle.END) bb._details = _new_button( None, "dialog-information", _SMALL_BUTTON_ICON_SIZE, tooltip=_("Show Technical Details"), toggle=True, clicked=_update_details, ) bb.add(bb._details) bb.set_child_secondary(bb._details, True) bb.set_child_non_homogeneous(bb._details, True) def _pair_new_device(trigger): assert _find_selected_device_id() is not None receiver = _find_selected_device() assert receiver is not None assert bool(receiver) assert receiver.kind is None action.pair(_window, receiver) bb._pair = _new_button(_("Pair new device"), "list-add", clicked=_pair_new_device) bb.add(bb._pair) def _unpair_current_device(trigger): assert _find_selected_device_id() is not None device = _find_selected_device() assert device is not None assert device.kind is not None action.unpair(_window, device) bb._unpair = _new_button(_("Unpair"), "edit-delete", clicked=_unpair_current_device) bb.add(bb._unpair) return bb def _create_empty_panel(): p = Gtk.Label() p.set_markup("<small>" + _("Select a device") + "</small>") p.set_sensitive(False) return p def _create_info_panel(): p = Gtk.Box.new(Gtk.Orientation.VERTICAL, 4) p._title = Gtk.Label(label=" ") p._icon = Gtk.Image() b1 = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 4) b1.pack_start(p._title, True, True, 0) b1.pack_start(p._icon, False, False, 0) p.pack_start(b1, False, False, 0) p.pack_start(Gtk.Separator.new(Gtk.Orientation.HORIZONTAL), False, False, 0) # spacer p._receiver = _create_receiver_panel() p.pack_start(p._receiver, True, True, 0) p._device = _create_device_panel() p.pack_start(p._device, True, True, 0) p.pack_start(Gtk.Separator.new(Gtk.Orientation.HORIZONTAL), False, False, 0) # spacer p._buttons = _create_buttons_box() p.pack_end(p._buttons, False, False, 0) return p def _create_tree(model): tree = Gtk.TreeView() tree.set_size_request(330, 0) # enough width for simple setups tree.set_headers_visible(False) tree.set_show_expanders(False) tree.set_level_indentation(20) tree.set_enable_tree_lines(True) tree.set_reorderable(False) tree.set_enable_search(False) tree.set_model(model) def _is_separator(model, item, _ignore=None): return model.get_value(item, _COLUMN.PATH) is None tree.set_row_separator_func(_is_separator, None) icon_cell_renderer = Gtk.CellRendererPixbuf() icon_cell_renderer.set_property("stock-size", _TREE_ICON_SIZE) icon_column = Gtk.TreeViewColumn("Icon", icon_cell_renderer) icon_column.add_attribute(icon_cell_renderer, "sensitive", _COLUMN.ACTIVE) icon_column.add_attribute(icon_cell_renderer, "icon-name", _COLUMN.ICON) tree.append_column(icon_column) name_cell_renderer = Gtk.CellRendererText() name_column = Gtk.TreeViewColumn("device name", name_cell_renderer) name_column.add_attribute(name_cell_renderer, "sensitive", _COLUMN.ACTIVE) name_column.add_attribute(name_cell_renderer, "text", _COLUMN.NAME) name_column.set_expand(True) tree.append_column(name_column) tree.set_expander_column(name_column) status_cell_renderer = Gtk.CellRendererText() status_cell_renderer.set_property("scale", 0.85) status_cell_renderer.set_property("xalign", 1) status_column = Gtk.TreeViewColumn("status text", status_cell_renderer) status_column.add_attribute(status_cell_renderer, "sensitive", _COLUMN.ACTIVE) status_column.add_attribute(status_cell_renderer, "text", _COLUMN.STATUS_TEXT) status_column.set_expand(True) tree.append_column(status_column) battery_cell_renderer = Gtk.CellRendererPixbuf() battery_cell_renderer.set_property("stock-size", _TREE_ICON_SIZE) battery_column = Gtk.TreeViewColumn("status icon", battery_cell_renderer) battery_column.add_attribute(battery_cell_renderer, "sensitive", _COLUMN.ACTIVE) battery_column.add_attribute(battery_cell_renderer, "icon-name", _COLUMN.STATUS_ICON) tree.append_column(battery_column) return tree def _create_window_layout(): assert _tree is not None assert _details is not None assert _info is not None assert _empty is not None assert _tree.get_selection().get_mode() == Gtk.SelectionMode.SINGLE _tree.get_selection().connect("changed", _device_selected) tree_scroll = Gtk.ScrolledWindow() tree_scroll.add(_tree) tree_scroll.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC) tree_scroll.set_shadow_type(Gtk.ShadowType.IN) tree_panel = Gtk.Box.new(Gtk.Orientation.VERTICAL, 0) tree_panel.set_homogeneous(False) tree_panel.pack_start(tree_scroll, True, True, 0) tree_panel.pack_start(_details, False, False, 0) panel = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 16) panel.pack_start(tree_panel, False, False, 0) panel.pack_start(_info, True, True, 0) panel.pack_start(_empty, True, True, 0) bottom_buttons_box = Gtk.HButtonBox() bottom_buttons_box.set_layout(Gtk.ButtonBoxStyle.START) bottom_buttons_box.set_spacing(20) quit_button = _new_button(_("Quit %s") % NAME, "application-exit", _SMALL_BUTTON_ICON_SIZE, clicked=destroy) bottom_buttons_box.add(quit_button) about_button = _new_button(_("About %s") % NAME, "help-about", _SMALL_BUTTON_ICON_SIZE, clicked=about.show) bottom_buttons_box.add(about_button) diversion_button = _new_button( _("Rule Editor"), "", _SMALL_BUTTON_ICON_SIZE, clicked=lambda *_trigger: diversion_rules.show_window(_model) ) bottom_buttons_box.add(diversion_button) bottom_buttons_box.set_child_secondary(diversion_button, True) vbox = Gtk.Box.new(Gtk.Orientation.VERTICAL, 8) vbox.set_border_width(8) vbox.pack_start(panel, True, True, 0) vbox.pack_end(bottom_buttons_box, False, False, 0) vbox.show_all() _details.set_visible(False) _info.set_visible(False) return vbox def _create(delete_action): window = Gtk.Window() window.set_title(NAME) window.set_role("status-window") window.connect("delete-event", delete_action) vbox = _create_window_layout() window.add(vbox) geometry = Gdk.Geometry() geometry.min_width = 600 geometry.min_height = 320 window.set_geometry_hints(vbox, geometry, Gdk.WindowHints.MIN_SIZE) window.set_position(Gtk.WindowPosition.CENTER) style = window.get_style_context() style.add_class("solaar") return window def _find_selected_device(): selection = _tree.get_selection() model, item = selection.get_selected() return model.get_value(item, _COLUMN.DEVICE) if item else None def _find_selected_device_id(): selection = _tree.get_selection() model, item = selection.get_selected() if item: return _model.get_value(item, _COLUMN.PATH), _model.get_value(item, _COLUMN.NUMBER) # triggered by changing selection in the tree def _device_selected(selection): model, item = selection.get_selected() device = model.get_value(item, _COLUMN.DEVICE) if item else None if device: _update_info_panel(device, full=True) else: # When removing a receiver, one of its children may get automatically selected # before the tree had time to remove them as well. # Rather than chase around for another device to select, just clear the selection. _tree.get_selection().unselect_all() _update_info_panel(None, full=True) def _receiver_row(receiver_path, receiver=None): assert receiver_path r = _model.get_iter_first() while r: r = _model.iter_next(r) item = _model.get_iter_first() while item: # first row matching the path must be the receiver one if _model.get_value(item, _COLUMN.PATH) == receiver_path: return item item = _model.iter_next(item) if not item and receiver: icon_name = icons.device_icon_name(receiver.name) status_text = None status_icon = None row_data = (receiver_path, 0, True, receiver.name, icon_name, status_text, status_icon, receiver) assert len(row_data) == len(_TREE_SEPATATOR) if logger.isEnabledFor(logging.DEBUG): logger.debug("new receiver row %s", row_data) item = _model.append(None, row_data) if _TREE_SEPATATOR: _model.append(None, _TREE_SEPATATOR) return item or None def _device_row(receiver_path, device_number, device=None): assert receiver_path assert device_number is not None receiver_row = _receiver_row(receiver_path, None if device is None else device.receiver) if device_number == 0xFF or device_number == 0x0: # direct-connected device, receiver row is device row if receiver_row: return receiver_row item = None new_child_index = 0 else: item = _model.iter_children(receiver_row) new_child_index = 0 while item: if _model.get_value(item, _COLUMN.PATH) != receiver_path: logger.warning( "path for device row %s different from path for receiver %s", _model.get_value(item, _COLUMN.PATH), receiver_path, ) item_number = _model.get_value(item, _COLUMN.NUMBER) if item_number == device_number: return item if item_number > device_number: item = None break new_child_index += 1 item = _model.iter_next(item) if not item and device: icon_name = icons.device_icon_name(device.name, device.kind) status_text = None status_icon = None row_data = ( receiver_path, device_number, bool(device.online), device.codename, icon_name, status_text, status_icon, device, ) assert len(row_data) == len(_TREE_SEPATATOR) if logger.isEnabledFor(logging.DEBUG): logger.debug("new device row %s at index %d", row_data, new_child_index) item = _model.insert(receiver_row, new_child_index, row_data) return item or None def select(receiver_path, device_number=None): assert _window assert receiver_path is not None if device_number is None: item = _receiver_row(receiver_path) else: item = _device_row(receiver_path, device_number) if item: selection = _tree.get_selection() selection.select_iter(item) else: logger.warning("select(%s, %s) failed to find an item", receiver_path, device_number) def _hide(w, _ignore=None): assert w == _window # some window managers move the window to 0,0 after hide() # so try to remember the last position position = _window.get_position() _window.hide() _window.move(*position) return True def popup(trigger=None, receiver_path=None, device_id=None): if receiver_path: select(receiver_path, device_id) _window.present() return True def toggle(trigger=None): if _window.get_visible(): _hide(_window) else: _window.present() def _update_details(button): assert button visible = button.get_active() if visible: # _details._text.set_markup('<small>reading...</small>') def _details_items(device, read_all=False): # If read_all is False, only return stuff that is ~100% already # cached, and involves no HID++ calls. yield _("Path"), device.path if device.kind is None: yield _("USB ID"), f"{LOGITECH_VENDOR_ID:04x}:" + device.product_id if read_all: yield _("Serial"), device.serial else: yield _("Serial"), "..." else: # yield ('Codename', device.codename) yield _("Index"), device.number if device.wpid: yield _("Wireless PID"), device.wpid if device.product_id: yield _("Product ID"), f"{LOGITECH_VENDOR_ID:04x}:" + device.product_id hid_version = device.protocol yield _("Protocol"), f"HID++ {hid_version:1.1f}" if hid_version else _("Unknown") if read_all and device.polling_rate: yield _("Polling rate"), device.polling_rate if read_all or not device.online: yield _("Serial"), device.serial else: yield _("Serial"), "..." if read_all and device.unitId and device.unitId != device.serial: yield _("Unit ID"), device.unitId if read_all: if device.firmware: for fw in list(device.firmware): yield " " + _(str(fw.kind)), (fw.name + " " + fw.version).strip() elif device.kind is None or device.online: yield f" {_('Firmware')}", "..." flag_bits = device.notification_flags if flag_bits is not None: flag_names = ( (f"({_('none')})",) if flag_bits == 0 else hidpp10_constants.NOTIFICATION_FLAG.flag_names(flag_bits) ) yield _("Notifications"), f"\n{' ':15}".join(flag_names) def _set_details(text): _details._text.set_markup(text) def _make_text(items): text = "\n".join("%-13s: %s" % (name, value) for name, value in items) return "<small><tt>" + text + "</tt></small>" def _displayable_items(items): for name, value in items: value = GLib.markup_escape_text(str(value).replace("\x00", "")).strip() if value: yield name, value def _read_slow(device): items = _details_items(selected_device, True) items = _displayable_items(items) text = _make_text(items) if device == _details._current_device: GLib.idle_add(_set_details, text) selected_device = _find_selected_device() assert selected_device _details._current_device = selected_device read_all = not (selected_device.kind is None or selected_device.online) items = _details_items(selected_device, read_all) _set_details(_make_text(items)) if read_all: _details._current_device = None else: ui_async(_read_slow, selected_device) _details.set_visible(visible) def _update_receiver_panel(receiver, panel, buttons, full=False): assert receiver devices_count = len(receiver) paired_text = ( _(_("No device paired.")) if devices_count == 0 else ngettext("%(count)s paired device.", "%(count)s paired devices.", devices_count) % {"count": devices_count} ) if receiver.max_devices > 0: paired_text += ( "\n\n<small>%s</small>" % ngettext( "Up to %(max_count)s device can be paired to this receiver.", "Up to %(max_count)s devices can be paired to this receiver.", receiver.max_devices, ) % {"max_count": receiver.max_devices} ) elif devices_count > 0: paired_text += f"\n\n<small>{_('Only one device can be paired to this receiver.')}</small>" pairings = receiver.remaining_pairings() if pairings is not None and pairings >= 0: paired_text += "\n<small>%s</small>" % ( ngettext("This receiver has %d pairing remaining.", "This receiver has %d pairings remaining.", pairings) % pairings ) panel._count.set_markup(paired_text) is_pairing = receiver.pairing.lock_open if is_pairing: panel._scanning.set_visible(True) if not panel._spinner.get_visible(): panel._spinner.start() panel._spinner.set_visible(True) else: panel._scanning.set_visible(False) if panel._spinner.get_visible(): panel._spinner.stop() panel._spinner.set_visible(False) panel.set_visible(True) # b._insecure.set_visible(False) buttons._unpair.set_visible(False) if ( not is_pairing and (receiver.remaining_pairings() is None or receiver.remaining_pairings() != 0) and (receiver.re_pairs or devices_count < receiver.max_devices) ): buttons._pair.set_sensitive(True) else: buttons._pair.set_sensitive(False) buttons._pair.set_visible(True) def _update_device_panel(device, panel, buttons, full=False): assert device is_online = bool(device.online) panel.set_sensitive(is_online) if device.battery_info is None or device.battery_info.level is None: device.read_battery() battery_level = device.battery_info.level if device.battery_info is not None else None battery_voltage = device.battery_info.voltage if device.battery_info is not None else None if battery_level is None and battery_voltage is None: panel._battery.set_visible(False) else: panel._battery.set_visible(True) battery_next_level = device.battery_info.next_level charging = device.battery_info.charging() if device.battery_info is not None else None icon_name = icons.battery(battery_level, charging) panel._battery._icon.set_from_icon_name(icon_name, _INFO_ICON_SIZE) panel._battery._icon.set_sensitive(True) panel._battery._text.set_sensitive(is_online) if battery_voltage is not None: panel._battery._label.set_text(_("Battery Voltage")) text = f"{int(battery_voltage)}mV" tooltip_text = _("Voltage reported by battery") else: panel._battery._label.set_text(_("Battery Level")) text = "" tooltip_text = _("Approximate level reported by battery") if battery_voltage is not None and battery_level is not None: text += ", " if battery_level is not None: text += _(str(battery_level)) if isinstance(battery_level, NamedInt) else f"{int(battery_level)}%" if battery_next_level is not None and not charging: if isinstance(battery_next_level, NamedInt): text += "<small> (" + _("next reported ") + _(str(battery_next_level)) + ")</small>" else: text += "<small> (" + _("next reported ") + f"{int(battery_next_level)}%" + ")</small>" tooltip_text = tooltip_text + _(" and next level to be reported.") if is_online: if charging: text += f" <small>({_('charging')})</small>" else: text += f" <small>({_('last known')})</small>" panel._battery._text.set_markup(text) panel._battery.set_tooltip_text(tooltip_text) if device.link_encrypted is None: panel._secure.set_visible(False) elif is_online: panel._secure.set_visible(True) panel._secure._icon.set_visible(True) if device.link_encrypted is True: panel._secure._text.set_text(_("encrypted")) panel._secure._icon.set_from_icon_name("security-high", _INFO_ICON_SIZE) panel._secure.set_tooltip_text(_("The wireless link between this device and its receiver is encrypted.")) else: panel._secure._text.set_text(_("not encrypted")) panel._secure._icon.set_from_icon_name("security-low", _INFO_ICON_SIZE) panel._secure.set_tooltip_text( _( "The wireless link between this device and its receiver is not encrypted.\n" "This is a security issue for pointing devices, and a major security issue for text-input devices." ) ) else: panel._secure.set_visible(True) panel._secure._icon.set_visible(False) panel._secure._text.set_markup(f"<small>{_('offline')}</small>") panel._secure.set_tooltip_text("") if is_online: light_level = device.battery_info.light_level if device.battery_info is not None else None if light_level is None: panel._lux.set_visible(False) else: panel._lux._icon.set_from_icon_name(icons.lux(light_level), _INFO_ICON_SIZE) panel._lux._text.set_text(_("%(light_level)d lux") % {"light_level": light_level}) panel._lux.set_visible(True) else: panel._lux.set_visible(False) buttons._pair.set_visible(False) buttons._unpair.set_sensitive(device.receiver.may_unpair if device.receiver else False) buttons._unpair.set_visible(True) panel.set_visible(True) if full: config_panel.update(device, is_online) def _update_info_panel(device, full=False): if device is None: # no selected device, show the 'empty' panel _details.set_visible(False) _info.set_visible(False) _empty.set_visible(True) return # a receiver must be valid # a device must be paired assert device _info._title.set_markup(f"<b>{device.name}</b>") icon_name = icons.device_icon_name(device.name, device.kind) _info._icon.set_from_icon_name(icon_name, _DEVICE_ICON_SIZE) if device.kind is None: _info._device.set_visible(False) _info._icon.set_sensitive(True) _info._title.set_sensitive(True) _update_receiver_panel(device, _info._receiver, _info._buttons, full) else: _info._receiver.set_visible(False) is_online = bool(device.online) _info._icon.set_sensitive(is_online) _info._title.set_sensitive(is_online) _update_device_panel(device, _info._device, _info._buttons, full) _empty.set_visible(False) _info.set_visible(True) if full: _update_details(_info._buttons._details) # window layout: # +--------------------------------+ # | tree | receiver | empty | # | | or device | | # |------------| status | | # | details | | | # |--------------------------------| # | (about) | # +--------------------------------| # either the status or empty panel is visible at any point # the details panel can be toggle on/off _model = None _tree = None _details = None _info = None _empty = None _window = None def init(show_window, hide_on_close): Gtk.Window.set_default_icon_name(NAME.lower()) global _model, _tree, _details, _info, _empty, _window _model = Gtk.TreeStore(*_COLUMN_TYPES) _tree = _create_tree(_model) _details = _create_details_panel() _info = _create_info_panel() _empty = _create_empty_panel() _window = _create(_hide if hide_on_close else destroy) if show_window: _window.present() def destroy(_ignore1=None, _ignore2=None): global _model, _tree, _details, _info, _empty, _window w, _window = _window, None w.destroy() w = None config_panel.destroy() _empty = None _info = None _details = None _tree = None _model = None def update(device, need_popup=False, refresh=False): if _window is None: return assert device is not None if need_popup: popup() selected_device_id = _find_selected_device_id() if device.kind is None: # receiver # receiver is_alive = bool(device) item = _receiver_row(device.path, device if is_alive else None) if is_alive and item: was_pairing = bool(_model.get_value(item, _COLUMN.STATUS_ICON)) is_pairing = (not device.isDevice) and bool(device.pairing.lock_open) _model.set_value(item, _COLUMN.STATUS_ICON, "network-wireless" if is_pairing else _CAN_SET_ROW_NONE) if selected_device_id == (device.path, 0): full_update = need_popup or was_pairing != is_pairing _update_info_panel(device, full=full_update) elif item: if _TREE_SEPATATOR: separator = _model.iter_next(item) if separator: _model.remove(separator) _model.remove(item) else: path = device.receiver.path if device.receiver is not None else device.path assert device.number is not None and device.number >= 0, "invalid device number" + str(device.number) item = _device_row(path, device.number, device if bool(device) else None) if bool(device) and item: update_device(device, item, selected_device_id, need_popup, full=refresh) elif item: _model.remove(item) config_panel.clean(device) # make sure all rows are visible _tree.expand_all() def update_device(device, item, selected_device_id, need_popup, full=False): was_online = _model.get_value(item, _COLUMN.ACTIVE) is_online = bool(device.online) _model.set_value(item, _COLUMN.ACTIVE, is_online) battery_level = device.battery_info.level if device.battery_info is not None else None battery_voltage = device.battery_info.voltage if device.battery_info is not None else None if battery_level is None: _model.set_value(item, _COLUMN.STATUS_TEXT, _CAN_SET_ROW_NONE) _model.set_value(item, _COLUMN.STATUS_ICON, _CAN_SET_ROW_NONE) else: if battery_voltage is not None and False: # Use levels instead of voltage here status_text = f"{int(battery_voltage)}mV" elif isinstance(battery_level, NamedInt): status_text = _(str(battery_level)) else: status_text = f"{int(battery_level)}%" _model.set_value(item, _COLUMN.STATUS_TEXT, status_text) charging = device.battery_info.charging() if device.battery_info is not None else None icon_name = icons.battery(battery_level, charging) _model.set_value(item, _COLUMN.STATUS_ICON, icon_name) _model.set_value(item, _COLUMN.NAME, device.codename) if selected_device_id is None or need_popup: select(device.receiver.path if device.receiver else device.path, device.number) elif selected_device_id == (device.receiver.path if device.receiver else device.path, device.number): full_update = full or was_online != is_online _update_info_panel(device, full=full_update) def find_device(serial): assert serial, "need serial number or unit ID to find a device" result = None def check(_store, _treepath, row): nonlocal result device = _model.get_value(row, _COLUMN.DEVICE) if device and device.kind and (device.unitId == serial or device.serial == serial): result = device return True _model.foreach(check) return result
31,960
Python
.py
728
36.217033
120
0.639807
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,481
pair_window.py
pwr-Solaar_Solaar/lib/solaar/ui/pair_window.py
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/ ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import logging from gi.repository import GLib from gi.repository import Gtk from logitech_receiver import hidpp10_constants from solaar.i18n import _ from solaar.i18n import ngettext from . import icons logger = logging.getLogger(__name__) _PAIRING_TIMEOUT = 30 # seconds _STATUS_CHECK = 500 # milliseconds def create(receiver): receiver.reset_pairing() # clear out any information on previous pairing title = _("%(receiver_name)s: pair new device") % {"receiver_name": receiver.name} if receiver.receiver_kind == "bolt": text = _("Bolt receivers are only compatible with Bolt devices.") text += "\n\n" text += _("Press a pairing button or key until the pairing light flashes quickly.") else: if receiver.receiver_kind == "unifying": text = _("Unifying receivers are only compatible with Unifying devices.") else: text = _("Other receivers are only compatible with a few devices.") text += "\n\n" text += _("For most devices, turn on the device you want to pair.") text += _("If the device is already turned on, turn it off and on again.") text += "\n" text += _("The device must not be paired with a nearby powered-on receiver.") text += "\n" text += _( "For devices with multiple channels, " "press, hold, and release the button for the channel you wish to pair" "\n" "or use the channel switch button to select a channel " "and then press, hold, and release the channel switch button." ) text += "\n" text += _("The channel indicator light should be blinking rapidly.") if receiver.remaining_pairings() and receiver.remaining_pairings() >= 0: text += ( ngettext( "\n\nThis receiver has %d pairing remaining.", "\n\nThis receiver has %d pairings remaining.", receiver.remaining_pairings(), ) % receiver.remaining_pairings() ) text += _("\nCancelling at this point will not use up a pairing.") ok = prepare(receiver) assistant = _create_assistant(receiver, ok, _finish, title, text) if ok: GLib.timeout_add(_STATUS_CHECK, check_lock_state, assistant, receiver) return assistant def prepare(receiver): if receiver.receiver_kind == "bolt": if receiver.discover(timeout=_PAIRING_TIMEOUT): return True else: receiver.pairing.error = "discovery did not start" return False elif receiver.set_lock(False, timeout=_PAIRING_TIMEOUT): return True else: receiver.pairing.error = "the pairing lock did not open" return False def check_lock_state(assistant, receiver, count=2): if not assistant.is_drawable(): if logger.isEnabledFor(logging.DEBUG): logger.debug("assistant %s destroyed, bailing out", assistant) return False return _check_lock_state(assistant, receiver, count) def _check_lock_state(assistant, receiver, count): if receiver.pairing.error: _pairing_failed(assistant, receiver, receiver.pairing.error) return False elif receiver.pairing.new_device: receiver.remaining_pairings(False) # Update remaining pairings _pairing_succeeded(assistant, receiver, receiver.pairing.new_device) return False elif not receiver.pairing.lock_open and not receiver.pairing.discovering: if count > 0: # the actual device notification may arrive later so have a little patience GLib.timeout_add(_STATUS_CHECK, check_lock_state, assistant, receiver, count - 1) else: _pairing_failed(assistant, receiver, "failed to open pairing lock") return False elif receiver.pairing.lock_open and receiver.pairing.device_passkey: _show_passcode(assistant, receiver, receiver.pairing.device_passkey) return True elif receiver.pairing.discovering and receiver.pairing.device_address and receiver.pairing.device_name: add = receiver.pairing.device_address ent = 20 if receiver.pairing.device_kind == hidpp10_constants.DEVICE_KIND.keyboard else 10 if receiver.pair_device(address=add, authentication=receiver.pairing.device_authentication, entropy=ent): return True else: _pairing_failed(assistant, receiver, "failed to open pairing lock") return False return True def _pairing_failed(assistant, receiver, error): assistant.remove_page(0) # needed to reset the window size if logger.isEnabledFor(logging.DEBUG): logger.debug("%s fail: %s", receiver, error) _create_failure_page(assistant, error) def _pairing_succeeded(assistant, receiver, device): assistant.remove_page(0) # needed to reset the window size if logger.isEnabledFor(logging.DEBUG): logger.debug("%s success: %s", receiver, device) _create_success_page(assistant, device) def _finish(assistant, receiver): if logger.isEnabledFor(logging.DEBUG): logger.debug("finish %s", assistant) assistant.destroy() receiver.pairing.new_device = None if receiver.pairing.lock_open: if receiver.receiver_kind == "bolt": receiver.pair_device("cancel") else: receiver.set_lock() if receiver.pairing.discovering: receiver.discover(True) if not receiver.pairing.lock_open and not receiver.pairing.discovering: receiver.pairing.error = None def _show_passcode(assistant, receiver, passkey): if logger.isEnabledFor(logging.DEBUG): logger.debug("%s show passkey: %s", receiver, passkey) name = receiver.pairing.device_name authentication = receiver.pairing.device_authentication intro_text = _("%(receiver_name)s: pair new device") % {"receiver_name": receiver.name} page_text = _("Enter passcode on %(name)s.") % {"name": name} page_text += "\n" if authentication & 0x01: page_text += _("Type %(passcode)s and then press the enter key.") % { "passcode": receiver.pairing.device_passkey, } else: passcode = ", ".join( [_("right") if bit == "1" else _("left") for bit in f"{int(receiver.pairing.device_passkey):010b}"] ) page_text += _("Press %(code)s\nand then press left and right buttons simultaneously.") % {"code": passcode} page = _create_page( assistant, Gtk.AssistantPageType.PROGRESS, intro_text, "preferences-desktop-peripherals", page_text, ) assistant.set_page_complete(page, True) assistant.next_page() def _create_assistant(receiver, ok, finish, title, text): assistant = Gtk.Assistant() assistant.set_title(title) assistant.set_icon_name("list-add") assistant.set_size_request(400, 240) assistant.set_resizable(False) assistant.set_role("pair-device") if ok: page_intro = _create_page( assistant, Gtk.AssistantPageType.PROGRESS, title, "preferences-desktop-peripherals", text, ) spinner = Gtk.Spinner() spinner.set_visible(True) spinner.start() page_intro.pack_end(spinner, True, True, 24) assistant.set_page_complete(page_intro, True) else: page_intro = _create_failure_page(assistant, receiver.pairing.error) assistant.connect("cancel", finish, receiver) assistant.connect("close", finish, receiver) return assistant def _create_success_page(assistant, device): def _check_encrypted(device, assistant, hbox): if assistant.is_drawable() and device.link_encrypted is False: hbox.pack_start(Gtk.Image.new_from_icon_name("security-low", Gtk.IconSize.MENU), False, False, 0) hbox.pack_start(Gtk.Label(label=_("The wireless link is not encrypted")), False, False, 0) hbox.show_all() return False page = _create_page(assistant, Gtk.AssistantPageType.SUMMARY) header = Gtk.Label(label=_("Found a new device:")) page.pack_start(header, False, False, 0) device_icon = Gtk.Image() icon_name = icons.device_icon_name(device.name, device.kind) device_icon.set_from_icon_name(icon_name, icons.LARGE_SIZE) page.pack_start(device_icon, True, True, 0) device_label = Gtk.Label() device_label.set_markup(f"<b>{device.name}</b>") page.pack_start(device_label, True, True, 0) hbox = Gtk.HBox(homogeneous=False, spacing=8) hbox.pack_start(Gtk.Label(label=" "), False, False, 0) hbox.set_property("expand", False) hbox.set_property("halign", Gtk.Align.CENTER) page.pack_start(hbox, False, False, 0) GLib.timeout_add(_STATUS_CHECK, _check_encrypted, device, assistant, hbox) # wait a bit to check link status page.show_all() assistant.next_page() assistant.commit() def _create_failure_page(assistant, error) -> None: header = _("Pairing failed") + ": " + _(str(error)) + "." if "timeout" in str(error): text = _("Make sure your device is within range, and has a decent battery charge.") elif str(error) == "device not supported": text = _("A new device was detected, but it is not compatible with this receiver.") elif "many" in str(error): text = _("More paired devices than receiver can support.") else: text = _("No further details are available about the error.") _create_page(assistant, Gtk.AssistantPageType.SUMMARY, header, "dialog-error", text) assistant.next_page() assistant.commit() def _create_page(assistant, kind, header=None, icon_name=None, text=None) -> Gtk.VBox: p = Gtk.VBox(homogeneous=False, spacing=8) assistant.append_page(p) assistant.set_page_type(p, kind) if header: item = Gtk.HBox(homogeneous=False, spacing=16) p.pack_start(item, False, True, 0) label = Gtk.Label(label=header) label.set_line_wrap(True) item.pack_start(label, True, True, 0) if icon_name: icon = Gtk.Image.new_from_icon_name(icon_name, Gtk.IconSize.DIALOG) item.pack_start(icon, False, False, 0) if text: label = Gtk.Label(label=text) label.set_line_wrap(True) p.pack_start(label, False, False, 0) p.show_all() return p
11,265
Python
.py
246
38.715447
116
0.66873
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,482
rule_conditions.py
pwr-Solaar_Solaar/lib/solaar/ui/rule_conditions.py
## Copyright (C) Solaar Contributors ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from dataclasses import dataclass from gi.repository import Gtk from logitech_receiver import diversion from logitech_receiver.diversion import Key from logitech_receiver.hidpp20 import SupportedFeature from logitech_receiver.special_keys import CONTROL from solaar.i18n import _ from solaar.ui.rule_base import CompletionEntry from solaar.ui.rule_base import RuleComponentUI class ConditionUI(RuleComponentUI): CLASS = diversion.Condition @classmethod def icon_name(cls): return "dialog-question" class ProcessUI(ConditionUI): CLASS = diversion.Process def create_widgets(self): self.widgets = {} self.label = Gtk.Label(valign=Gtk.Align.CENTER, hexpand=True) self.label.set_text(_("X11 active process. For use in X11 only.")) self.widgets[self.label] = (0, 0, 1, 1) self.field = Gtk.Entry(halign=Gtk.Align.CENTER, valign=Gtk.Align.CENTER, hexpand=True) self.field.set_size_request(600, 0) self.field.connect("changed", self._on_update) self.widgets[self.field] = (0, 1, 1, 1) def show(self, component, editable=True): super().show(component, editable) with self.ignore_changes(): self.field.set_text(component.process) def collect_value(self): return self.field.get_text() @classmethod def left_label(cls, component): return _("Process") @classmethod def right_label(cls, component): return str(component.process) class MouseProcessUI(ConditionUI): CLASS = diversion.MouseProcess def create_widgets(self): self.widgets = {} self.label = Gtk.Label(valign=Gtk.Align.CENTER, hexpand=True) self.label.set_text(_("X11 mouse process. For use in X11 only.")) self.widgets[self.label] = (0, 0, 1, 1) self.field = Gtk.Entry(halign=Gtk.Align.CENTER, valign=Gtk.Align.CENTER, hexpand=True) self.field.set_size_request(600, 0) self.field.connect("changed", self._on_update) self.widgets[self.field] = (0, 1, 1, 1) def show(self, component, editable=True): super().show(component, editable) with self.ignore_changes(): self.field.set_text(component.process) def collect_value(self): return self.field.get_text() @classmethod def left_label(cls, component): return _("MouseProcess") @classmethod def right_label(cls, component): return str(component.process) class FeatureUI(ConditionUI): CLASS = diversion.Feature FEATURES_WITH_DIVERSION = [ str(SupportedFeature.CROWN), str(SupportedFeature.THUMB_WHEEL), str(SupportedFeature.LOWRES_WHEEL), str(SupportedFeature.HIRES_WHEEL), str(SupportedFeature.GESTURE_2), str(SupportedFeature.REPROG_CONTROLS_V4), str(SupportedFeature.GKEY), str(SupportedFeature.MKEYS), str(SupportedFeature.MR), ] def create_widgets(self): self.widgets = {} self.label = Gtk.Label(valign=Gtk.Align.CENTER, hexpand=True) self.label.set_text(_("Feature name of notification triggering rule processing.")) self.widgets[self.label] = (0, 0, 1, 1) self.field = Gtk.ComboBoxText.new_with_entry() self.field.append("", "") for feature in self.FEATURES_WITH_DIVERSION: self.field.append(feature, feature) self.field.set_valign(Gtk.Align.CENTER) self.field.set_size_request(600, 0) self.field.connect("changed", self._on_update) all_features = [str(f) for f in SupportedFeature] CompletionEntry.add_completion_to_entry(self.field.get_child(), all_features) self.widgets[self.field] = (0, 1, 1, 1) def show(self, component, editable=True): super().show(component, editable) with self.ignore_changes(): f = str(component.feature) if component.feature else "" self.field.set_active_id(f) if f not in self.FEATURES_WITH_DIVERSION: self.field.get_child().set_text(f) def collect_value(self): return (self.field.get_active_text() or "").strip() def _on_update(self, *args): super()._on_update(*args) icon = "dialog-warning" if not self.component.feature else "" self.field.get_child().set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, icon) @classmethod def left_label(cls, component): return _("Feature") @classmethod def right_label(cls, component): return f"{str(component.feature)} ({int(component.feature or 0):04X})" class ReportUI(ConditionUI): CLASS = diversion.Report MIN_VALUE = -1 # for invalid values MAX_VALUE = 15 def create_widgets(self): self.widgets = {} self.label = Gtk.Label(valign=Gtk.Align.CENTER, hexpand=True) self.label.set_text(_("Report number of notification triggering rule processing.")) self.widgets[self.label] = (0, 0, 1, 1) self.field = Gtk.SpinButton.new_with_range(self.MIN_VALUE, self.MAX_VALUE, 1) self.field.set_halign(Gtk.Align.CENTER) self.field.set_valign(Gtk.Align.CENTER) self.field.set_hexpand(True) self.field.connect("changed", self._on_update) self.widgets[self.field] = (0, 1, 1, 1) def show(self, component, editable=True): super().show(component, editable) with self.ignore_changes(): self.field.set_value(component.report) def collect_value(self): return int(self.field.get_value()) @classmethod def left_label(cls, component): return _("Report") @classmethod def right_label(cls, component): return str(component.report) class ModifiersUI(ConditionUI): CLASS = diversion.Modifiers def create_widgets(self): self.widgets = {} self.label = Gtk.Label(valign=Gtk.Align.CENTER, hexpand=True) self.label.set_text(_("Active keyboard modifiers. Not always available in Wayland.")) self.widgets[self.label] = (0, 0, 5, 1) self.labels = {} self.switches = {} for i, m in enumerate(diversion.MODIFIERS): switch = Gtk.Switch(halign=Gtk.Align.CENTER, valign=Gtk.Align.START, hexpand=True) label = Gtk.Label(label=m, halign=Gtk.Align.CENTER, valign=Gtk.Align.END, hexpand=True) self.widgets[label] = (i, 1, 1, 1) self.widgets[switch] = (i, 2, 1, 1) self.labels[m] = label self.switches[m] = switch switch.connect("notify::active", self._on_update) def show(self, component, editable=True): super().show(component, editable) with self.ignore_changes(): for m in diversion.MODIFIERS: self.switches[m].set_active(m in component.modifiers) def collect_value(self): return [m for m, s in self.switches.items() if s.get_active()] @classmethod def left_label(cls, component): return _("Modifiers") @classmethod def right_label(cls, component): return "+".join(component.modifiers) or "None" class KeyUI(ConditionUI): CLASS = diversion.Key KEY_NAMES = map(str, CONTROL) def create_widgets(self): self.widgets = {} self.label = Gtk.Label(valign=Gtk.Align.CENTER, hexpand=True) self.label.set_text( _( "Diverted key or button depressed or released.\n" "Use the Key/Button Diversion and Divert G Keys settings to divert keys and buttons." ) ) self.widgets[self.label] = (0, 0, 5, 1) self.key_field = CompletionEntry(self.KEY_NAMES, halign=Gtk.Align.CENTER, valign=Gtk.Align.CENTER, hexpand=True) self.key_field.set_size_request(600, 0) self.key_field.connect("changed", self._on_update) self.widgets[self.key_field] = (0, 1, 2, 1) self.action_pressed_radio = Gtk.RadioButton.new_with_label_from_widget(None, _("Key down")) self.action_pressed_radio.connect("toggled", self._on_update, Key.DOWN) self.widgets[self.action_pressed_radio] = (2, 1, 1, 1) self.action_released_radio = Gtk.RadioButton.new_with_label_from_widget(self.action_pressed_radio, _("Key up")) self.action_released_radio.connect("toggled", self._on_update, Key.UP) self.widgets[self.action_released_radio] = (3, 1, 1, 1) def show(self, component, editable=True): super().show(component, editable) with self.ignore_changes(): self.key_field.set_text(str(component.key) if self.component.key else "") if not component.action or component.action == Key.DOWN: self.action_pressed_radio.set_active(True) else: self.action_released_radio.set_active(True) def collect_value(self): action = Key.UP if self.action_released_radio.get_active() else Key.DOWN return [self.key_field.get_text(), action] def _on_update(self, *args): super()._on_update(*args) icon = "dialog-warning" if not self.component.key or not self.component.action else "" self.key_field.set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, icon) @classmethod def left_label(cls, component): return _("Key") @classmethod def right_label(cls, component): return f"{str(component.key)} ({int(component.key):04X}) ({_(component.action)})" if component.key else "None" class KeyIsDownUI(ConditionUI): CLASS = diversion.KeyIsDown KEY_NAMES = map(str, CONTROL) def create_widgets(self): self.widgets = {} self.label = Gtk.Label(valign=Gtk.Align.CENTER, hexpand=True) self.label.set_text( _( "Diverted key or button is currently down.\n" "Use the Key/Button Diversion and Divert G Keys settings to divert keys and buttons." ) ) self.widgets[self.label] = (0, 0, 5, 1) self.key_field = CompletionEntry(self.KEY_NAMES, halign=Gtk.Align.CENTER, valign=Gtk.Align.CENTER, hexpand=True) self.key_field.set_size_request(600, 0) self.key_field.connect("changed", self._on_update) self.widgets[self.key_field] = (0, 1, 1, 1) def show(self, component, editable=True): super().show(component, editable) with self.ignore_changes(): self.key_field.set_text(str(component.key) if self.component.key else "") def collect_value(self): return self.key_field.get_text() def _on_update(self, *args): super()._on_update(*args) icon = "dialog-warning" if not self.component.key else "" self.key_field.set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, icon) @classmethod def left_label(cls, component): return _("KeyIsDown") @classmethod def right_label(cls, component): return f"{str(component.key)} ({int(component.key):04X})" if component.key else "None" class TestUI(ConditionUI): CLASS = diversion.Test def create_widgets(self): self.widgets = {} self.label = Gtk.Label(valign=Gtk.Align.CENTER, hexpand=True) self.label.set_text(_("Test condition on notification triggering rule processing.")) self.widgets[self.label] = (0, 0, 4, 1) lbl = Gtk.Label(label=_("Test"), halign=Gtk.Align.CENTER, valign=Gtk.Align.END, hexpand=False, vexpand=False) self.widgets[lbl] = (0, 1, 1, 1) lbl = Gtk.Label(label=_("Parameter"), halign=Gtk.Align.CENTER, valign=Gtk.Align.END, hexpand=False, vexpand=False) self.widgets[lbl] = (2, 1, 1, 1) self.test = Gtk.ComboBoxText.new_with_entry() self.test.append("", "") for t in diversion.TESTS: self.test.append(t, t) self.test.set_halign(Gtk.Align.END) self.test.set_valign(Gtk.Align.CENTER) self.test.set_hexpand(False) self.test.set_size_request(300, 0) CompletionEntry.add_completion_to_entry(self.test.get_child(), diversion.TESTS) self.test.connect("changed", self._on_update) self.widgets[self.test] = (1, 1, 1, 1) self.parameter = Gtk.Entry(halign=Gtk.Align.CENTER, valign=Gtk.Align.END, hexpand=True) self.parameter.set_size_request(150, 0) self.parameter.connect("changed", self._on_update) self.widgets[self.parameter] = (3, 1, 1, 1) def show(self, component, editable=True): super().show(component, editable) with self.ignore_changes(): self.test.set_active_id(component.test) self.parameter.set_text(str(component.parameter) if component.parameter is not None else "") if component.test not in diversion.TESTS: self.test.get_child().set_text(component.test) self._change_status_icon() def collect_value(self): try: param = int(self.parameter.get_text()) if self.parameter.get_text() else None except Exception: param = self.parameter.get_text() test = (self.test.get_active_text() or "").strip() return [test, param] if param is not None else [test] def _on_update(self, *args): super()._on_update(*args) self._change_status_icon() def _change_status_icon(self): icon = "dialog-warning" if (self.test.get_active_text() or "").strip() not in diversion.TESTS else "" self.test.get_child().set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, icon) @classmethod def left_label(cls, component): return _("Test") @classmethod def right_label(cls, component): return component.test + (" " + repr(component.parameter) if component.parameter is not None else "") @dataclass class TestBytesElement: id: str label: str min: int max: int @dataclass class TestBytesMode: label: str elements: list label_fn: callable class TestBytesUI(ConditionUI): CLASS = diversion.TestBytes _common_elements = [ TestBytesElement("begin", _("begin (inclusive)"), 0, 16), TestBytesElement("end", _("end (exclusive)"), 0, 16), ] _global_min = -(2**31) _global_max = 2**31 - 1 _modes = { "range": TestBytesMode( _("range"), _common_elements + [ TestBytesElement("minimum", _("minimum"), _global_min, _global_max), # uint32 TestBytesElement("maximum", _("maximum"), _global_min, _global_max), ], lambda e: _("bytes %(0)d to %(1)d, ranging from %(2)d to %(3)d" % {str(i): v for i, v in enumerate(e)}), ), "mask": TestBytesMode( _("mask"), _common_elements + [TestBytesElement("mask", _("mask"), _global_min, _global_max)], lambda e: _("bytes %(0)d to %(1)d, mask %(2)d" % {str(i): v for i, v in enumerate(e)}), ), } def create_widgets(self): self.fields = {} self.field_labels = {} self.widgets = {} self.label = Gtk.Label(valign=Gtk.Align.CENTER, hexpand=True) self.label.set_text(_("Bit or range test on bytes in notification message triggering rule processing.")) self.widgets[self.label] = (0, 0, 5, 1) col = 0 mode_col = 2 self.mode_field = Gtk.ComboBox.new_with_model(Gtk.ListStore(str, str)) mode_renderer = Gtk.CellRendererText() self.mode_field.set_id_column(0) self.mode_field.pack_start(mode_renderer, True) self.mode_field.add_attribute(mode_renderer, "text", 1) self.widgets[self.mode_field] = (mode_col, 2, 1, 1) mode_label = Gtk.Label(label=_("type"), margin_top=20) self.widgets[mode_label] = (mode_col, 1, 1, 1) for mode_id, mode in TestBytesUI._modes.items(): self.mode_field.get_model().append([mode_id, mode.label]) for element in mode.elements: if element.id not in self.fields: field = Gtk.SpinButton.new_with_range(element.min, element.max, 1) field.set_value(0) field.set_size_request(150, 0) field.connect("value-changed", self._on_update) label = Gtk.Label(label=element.label, margin_top=20) self.fields[element.id] = field self.field_labels[element.id] = label self.widgets[label] = (col, 1, 1, 1) self.widgets[field] = (col, 2, 1, 1) col += 1 if col != mode_col - 1 else 2 self.mode_field.connect("changed", lambda cb: (self._on_update(), self._only_mode(cb.get_active_id()))) self.mode_field.set_active_id("range") def show(self, component, editable=True): super().show(component, editable) with self.ignore_changes(): mode_id = {3: "mask", 4: "range"}.get(len(component.test), None) self._only_mode(mode_id) if not mode_id: return self.mode_field.set_active_id(mode_id) if mode_id: mode = TestBytesUI._modes[mode_id] for i, element in enumerate(mode.elements): self.fields[element.id].set_value(component.test[i]) def collect_value(self): mode_id = self.mode_field.get_active_id() return [self.fields[element.id].get_value_as_int() for element in TestBytesUI._modes[mode_id].elements] def _only_mode(self, mode_id): if not mode_id: return keep = {element.id for element in TestBytesUI._modes[mode_id].elements} for element_id, f in self.fields.items(): visible = element_id in keep f.set_visible(visible) self.field_labels[element_id].set_visible(visible) def _on_update(self, *args): super()._on_update(*args) if not self.component: return begin, end, *etc = self.component.test icon = "dialog-warning" if end <= begin else "" self.fields["end"].set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, icon) if len(self.component.test) == 4: *etc, minimum, maximum = self.component.test icon = "dialog-warning" if maximum < minimum else "" self.fields["maximum"].set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, icon) @classmethod def left_label(cls, component): return _("Test bytes") @classmethod def right_label(cls, component): mode_id = {3: "mask", 4: "range"}.get(len(component.test), None) if not mode_id: return str(component.test) return TestBytesUI._modes[mode_id].label_fn(component.test) class MouseGestureUI(ConditionUI): CLASS = diversion.MouseGesture MOUSE_GESTURE_NAMES = [ "Mouse Up", "Mouse Down", "Mouse Left", "Mouse Right", "Mouse Up-left", "Mouse Up-right", "Mouse Down-left", "Mouse Down-right", ] MOVE_NAMES = list(map(str, CONTROL)) + MOUSE_GESTURE_NAMES def create_widgets(self): self.widgets = {} self.fields = [] self.label = Gtk.Label( label=_("Mouse gesture with optional initiating button followed by zero or more mouse movements."), halign=Gtk.Align.CENTER, ) self.widgets[self.label] = (0, 0, 5, 1) self.del_btns = [] self.add_btn = Gtk.Button(label=_("Add movement"), halign=Gtk.Align.CENTER, valign=Gtk.Align.END, hexpand=True) self.add_btn.connect("clicked", self._clicked_add) self.widgets[self.add_btn] = (1, 1, 1, 1) def _create_field(self): field = Gtk.ComboBoxText.new_with_entry() for g in self.MOUSE_GESTURE_NAMES: field.append(g, g) CompletionEntry.add_completion_to_entry(field.get_child(), self.MOVE_NAMES) field.connect("changed", self._on_update) self.fields.append(field) self.widgets[field] = (len(self.fields) - 1, 1, 1, 1) return field def _create_del_btn(self): btn = Gtk.Button(label=_("Delete"), halign=Gtk.Align.CENTER, valign=Gtk.Align.START, hexpand=True) self.del_btns.append(btn) self.widgets[btn] = (len(self.del_btns) - 1, 2, 1, 1) btn.connect("clicked", self._clicked_del, len(self.del_btns) - 1) return btn def _clicked_add(self, _btn): self.component.__init__(self.collect_value() + [""], warn=False) self.show(self.component, editable=True) self.fields[len(self.component.movements) - 1].grab_focus() def _clicked_del(self, _btn, pos): v = self.collect_value() v.pop(pos) self.component.__init__(v, warn=False) self.show(self.component, editable=True) self._on_update_callback() def _on_update(self, *args): super()._on_update(*args) for i, f in enumerate(self.fields): if f.get_visible(): icon = ( "dialog-warning" if i < len(self.component.movements) and self.component.movements[i] not in self.MOVE_NAMES else "" ) f.get_child().set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, icon) def show(self, component, editable=True): n = len(component.movements) while len(self.fields) < n: self._create_field() self._create_del_btn() self.widgets[self.add_btn] = (n + 1, 1, 1, 1) super().show(component, editable) for i in range(n): field = self.fields[i] with self.ignore_changes(): field.get_child().set_text(component.movements[i]) field.set_size_request(int(0.3 * self.panel.get_toplevel().get_size()[0]), 0) field.show_all() self.del_btns[i].show() for i in range(n, len(self.fields)): self.fields[i].hide() self.del_btns[i].hide() self.add_btn.set_valign(Gtk.Align.END if n >= 1 else Gtk.Align.CENTER) def collect_value(self): return [f.get_active_text().strip() for f in self.fields if f.get_visible()] @classmethod def left_label(cls, component): return _("Mouse Gesture") @classmethod def right_label(cls, component): if len(component.movements) == 0: return "No-op" else: return " -> ".join(component.movements)
23,337
Python
.py
509
37.011788
122
0.627645
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,483
config_panel.py
pwr-Solaar_Solaar/lib/solaar/ui/config_panel.py
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/ ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import logging import traceback from threading import Timer import gi from logitech_receiver import hidpp20 from logitech_receiver import settings from solaar.i18n import _ from solaar.i18n import ngettext from .common import ui_async gi.require_version("Gtk", "3.0") from gi.repository import Gdk # NOQA: E402 from gi.repository import GLib # NOQA: E402 from gi.repository import Gtk # NOQA: E402 logger = logging.getLogger(__name__) def _read_async(setting, force_read, sbox, device_is_online, sensitive): def _do_read(s, force, sb, online, sensitive): try: v = s.read(not force) except Exception as e: v = None if logger.isEnabledFor(logging.WARNING): logger.warning("%s: error reading so use None (%s): %s", s.name, s._device, repr(e)) GLib.idle_add(_update_setting_item, sb, v, online, sensitive, True, priority=99) ui_async(_do_read, setting, force_read, sbox, device_is_online, sensitive) def _write_async(setting, value, sbox, sensitive=True, key=None): def _do_write(_s, v, sb, key): try: if key is None: v = setting.write(v) else: v = setting.write_key_value(key, v) v = {key: v} except Exception: traceback.print_exc() v = None if sb: GLib.idle_add(_update_setting_item, sb, v, True, sensitive, priority=99) if sbox: sbox._control.set_sensitive(False) sbox._failed.set_visible(False) sbox._spinner.set_visible(True) sbox._spinner.start() ui_async(_do_write, setting, value, sbox, key) class ComboBoxText(Gtk.ComboBoxText): def get_value(self): return int(self.get_active_id()) def set_value(self, value): return self.set_active_id(str(int(value))) class Scale(Gtk.Scale): def get_value(self): return int(super().get_value()) class Control: def __init__(self, **kwargs): self.sbox = None self.delegate = None def init(self, sbox, delegate): self.sbox = sbox self.delegate = delegate if delegate else self def changed(self, *args): if self.get_sensitive(): self.delegate.update() def update(self): _write_async(self.sbox.setting, self.get_value(), self.sbox) def layout(self, sbox, label, change, spinner, failed): sbox.pack_start(label, False, False, 0) sbox.pack_end(change, False, False, 0) fill = sbox.setting.kind == settings.KIND.range or sbox.setting.kind == settings.KIND.hetero sbox.pack_end(self, fill, fill, 0) sbox.pack_end(spinner, False, False, 0) sbox.pack_end(failed, False, False, 0) return self class ToggleControl(Gtk.Switch, Control): def __init__(self, sbox, delegate=None): super().__init__(halign=Gtk.Align.CENTER, valign=Gtk.Align.CENTER) self.init(sbox, delegate) self.connect("notify::active", self.changed) def set_value(self, value): if value is not None: self.set_state(value) def get_value(self): return self.get_state() class SliderControl(Gtk.Scale, Control): def __init__(self, sbox, delegate=None): super().__init__(halign=Gtk.Align.FILL) self.init(sbox, delegate) self.timer = None self.set_range(*self.sbox.setting.range) self.set_round_digits(0) self.set_digits(0) self.set_increments(1, 5) self.connect("value-changed", self.changed) def get_value(self): return int(super().get_value()) def changed(self, *args): if self.get_sensitive(): if self.timer: self.timer.cancel() self.timer = Timer(0.5, lambda: GLib.idle_add(self.do_change)) self.timer.start() def do_change(self): self.timer.cancel() self.update() def _create_choice_control(sbox, delegate=None, choices=None): if 50 > len(choices if choices else sbox.setting.choices): return ChoiceControlLittle(sbox, choices=choices, delegate=delegate) else: return ChoiceControlBig(sbox, choices=choices, delegate=delegate) # GTK boxes have property lists, but the keys must be strings class ChoiceControlLittle(Gtk.ComboBoxText, Control): def __init__(self, sbox, delegate=None, choices=None): super().__init__(halign=Gtk.Align.FILL) self.init(sbox, delegate) self.choices = choices if choices is not None else sbox.setting.choices for entry in self.choices: self.append(str(int(entry)), str(entry)) self.connect("changed", self.changed) def get_value(self): return int(self.get_active_id()) if self.get_active_id() is not None else None def set_value(self, value): if value is not None: self.set_active_id(str(int(value))) def get_choice(self): id = self.get_value() return next((x for x in self.choices if x == id), None) def set_choices(self, choices): self.remove_all() for choice in choices: self.append(str(int(choice)), _(str(choice))) class ChoiceControlBig(Gtk.Entry, Control): def __init__(self, sbox, delegate=None, choices=None): super().__init__(halign=Gtk.Align.FILL) self.init(sbox, delegate) self.choices = choices if choices is not None else sbox.setting.choices self.value = None self.set_width_chars(max([len(str(x)) for x in self.choices]) + 5) liststore = Gtk.ListStore(int, str) for v in self.choices: liststore.append((int(v), str(v))) completion = Gtk.EntryCompletion() completion.set_model(liststore) def norm(s): return s.replace("_", "").replace(" ", "").lower() completion.set_match_func(lambda completion, key, it: norm(key) in norm(completion.get_model()[it][1])) completion.set_text_column(1) self.set_completion(completion) self.connect("changed", self.changed) self.connect("activate", self.activate) completion.connect("match_selected", self.select) def get_value(self): choice = self.get_choice() return int(choice) if choice is not None else None def set_value(self, value): if value is not None: self.set_text(str(next((x for x in self.choices if x == value), None))) def get_choice(self): key = self.get_text() return next((x for x in self.choices if x == key), None) def changed(self, *args): self.value = self.get_choice() icon = "dialog-warning" if self.value is None else "dialog-question" if self.get_sensitive() else "" self.set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, icon) tooltip = _("Incomplete") if self.value is None else _("Complete - ENTER to change") self.set_icon_tooltip_text(Gtk.EntryIconPosition.SECONDARY, tooltip) def activate(self, *_args): if self.value is not None and self.get_sensitive(): self.set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, "") self.delegate.update() def select(self, _completion, model, iter): self.set_value(model.get(iter, 0)[0]) if self.value and self.get_sensitive(): self.set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, "") self.delegate.update() class MapChoiceControl(Gtk.HBox, Control): def __init__(self, sbox, delegate=None): super().__init__(homogeneous=False, spacing=6) self.init(sbox, delegate) self.keyBox = Gtk.ComboBoxText() for entry in sbox.setting.choices: self.keyBox.append(str(int(entry)), _(str(entry))) self.keyBox.set_active(0) key_choice = int(self.keyBox.get_active_id()) self.value_choices = self.sbox.setting.choices[key_choice] self.valueBox = _create_choice_control(sbox.setting, choices=self.value_choices, delegate=self) self.pack_start(self.keyBox, False, False, 0) self.pack_end(self.valueBox, False, False, 0) self.keyBox.connect("changed", self.map_value_notify_key) def get_value(self): key_choice = int(self.keyBox.get_active_id()) if key_choice is not None and self.valueBox.get_value() is not None: return self.valueBox.get_value() def set_value(self, value): if value is None: return self.valueBox.set_sensitive(self.get_sensitive()) key = int(self.keyBox.get_active_id()) if value.get(key) is not None: self.valueBox.set_value(value.get(key)) self.valueBox.set_sensitive(True) def map_populate_value_box(self, key_choice): choices = self.sbox.setting.choices[key_choice] if choices != self.value_choices: self.value_choices = choices self.valueBox.remove_all() self.valueBox.set_choices(choices) current = self.sbox.setting._value.get(key_choice) if self.sbox.setting._value else None if current is not None: self.valueBox.set_value(current) def map_value_notify_key(self, *_args): key_choice = int(self.keyBox.get_active_id()) if self.keyBox.get_sensitive(): self.map_populate_value_box(key_choice) def update(self): key_choice = int(self.keyBox.get_active_id()) value = self.get_value() if value is not None and self.valueBox.get_sensitive() and self.sbox.setting._value.get(key_choice) != value: self.sbox.setting._value[int(key_choice)] = value _write_async(self.sbox.setting, value, self.sbox, key=int(key_choice)) class MultipleControl(Gtk.ListBox, Control): def __init__(self, sbox, change, button_label="...", delegate=None): super().__init__() self.init(sbox, delegate) self.set_selection_mode(Gtk.SelectionMode.NONE) self.set_no_show_all(True) self._showing = True self.setup(sbox.setting) # set up the data and boxes for the sub-controls btn = Gtk.Button(label=button_label) btn.connect("clicked", self.toggle_display) self._button = btn hbox = Gtk.HBox(homogeneous=False, spacing=6) hbox.pack_end(change, False, False, 0) hbox.pack_end(btn, False, False, 0) self._header = hbox vbox = Gtk.VBox(homogeneous=False, spacing=6) vbox.pack_start(hbox, True, True, 0) vbox.pack_end(self, True, True, 0) self.vbox = vbox self.toggle_display() _disable_listbox_highlight_bg(self) def layout(self, sbox, label, change, spinner, failed): self._header.pack_start(label, False, False, 0) self._header.pack_end(spinner, False, False, 0) self._header.pack_end(failed, False, False, 0) sbox.pack_start(self.vbox, True, True, 0) sbox._button = self._button return True def toggle_display(self, *_args): self._showing = not self._showing if not self._showing: for c in self.get_children(): c.hide() self.hide() else: self.show() for c in self.get_children(): c.show_all() class MultipleToggleControl(MultipleControl): def setup(self, setting): self._label_control_pairs = [] for k in setting._validator.get_options(): h = Gtk.HBox(homogeneous=False, spacing=0) lbl_text = str(k) lbl_tooltip = None if hasattr(setting, "_labels"): l1, l2 = setting._labels.get(k, (None, None)) lbl_text = l1 if l1 else lbl_text lbl_tooltip = l2 if l2 else lbl_tooltip lbl = Gtk.Label(label=lbl_text) h.set_tooltip_text(lbl_tooltip or " ") control = Gtk.Switch() control._setting_key = int(k) control.connect("notify::active", self.toggle_notify) h.pack_start(lbl, False, False, 0) h.pack_end(control, False, False, 0) lbl.set_margin_start(30) self.add(h) self._label_control_pairs.append((lbl, control)) def toggle_notify(self, switch, _active): if switch.get_sensitive(): key = switch._setting_key new_state = switch.get_state() if self.sbox.setting._value[key] != new_state: self.sbox.setting._value[key] = new_state _write_async(self.sbox.setting, new_state, self.sbox, key=int(key)) def set_value(self, value): if value is None: return active = 0 total = len(self._label_control_pairs) to_join = [] for lbl, elem in self._label_control_pairs: v = value.get(elem._setting_key, None) if v is not None: elem.set_state(v) if elem.get_state(): active += 1 to_join.append(lbl.get_text() + ": " + str(elem.get_state())) b = ", ".join(to_join) self._button.set_label(f"{active} / {total}") self._button.set_tooltip_text(b) class MultipleRangeControl(MultipleControl): def setup(self, setting): self._items = [] for item in setting._validator.items: lbl_text = str(item) lbl_tooltip = None if hasattr(setting, "_labels"): l1, l2 = setting._labels.get(int(item), (None, None)) lbl_text = l1 if l1 else lbl_text lbl_tooltip = l2 if l2 else lbl_tooltip item_lbl = Gtk.Label(label=lbl_text) self.add(item_lbl) self.set_tooltip_text(lbl_tooltip or " ") item_lb = Gtk.ListBox() item_lb.set_selection_mode(Gtk.SelectionMode.NONE) item_lb._sub_items = [] for sub_item in setting._validator.sub_items[item]: h = Gtk.HBox(homogeneous=False, spacing=20) lbl_text = str(sub_item) lbl_tooltip = None if hasattr(setting, "_labels_sub"): l1, l2 = setting._labels_sub.get(str(sub_item), (None, None)) lbl_text = l1 if l1 else lbl_text lbl_tooltip = l2 if l2 else lbl_tooltip sub_item_lbl = Gtk.Label(label=lbl_text) h.set_tooltip_text(lbl_tooltip or " ") h.pack_start(sub_item_lbl, False, False, 0) sub_item_lbl.set_margin_start(30) if sub_item.widget == "Scale": control = Gtk.Scale.new_with_range( Gtk.Orientation.HORIZONTAL, sub_item.minimum, sub_item.maximum, 1, ) control.set_round_digits(0) control.set_digits(0) h.pack_end(control, True, True, 0) elif sub_item.widget == "SpinButton": control = Gtk.SpinButton.new_with_range(sub_item.minimum, sub_item.maximum, 1) control.set_digits(0) h.pack_end(control, False, False, 0) else: raise NotImplementedError control.connect("value-changed", self.changed, item, sub_item) item_lb.add(h) h._setting_sub_item = sub_item h._label, h._control = sub_item_lbl, control item_lb._sub_items.append(h) item_lb._setting_item = item _disable_listbox_highlight_bg(item_lb) self.add(item_lb) self._items.append(item_lb) def changed(self, control, item, sub_item): if control.get_sensitive(): if hasattr(control, "_timer"): control._timer.cancel() control._timer = Timer(0.5, lambda: GLib.idle_add(self._write, control, item, sub_item)) control._timer.start() def _write(self, control, item, sub_item): control._timer.cancel() delattr(control, "_timer") new_state = int(control.get_value()) if self.sbox.setting._value[int(item)][str(sub_item)] != new_state: self.sbox.setting._value[int(item)][str(sub_item)] = new_state _write_async(self.sbox.setting, self.sbox.setting._value[int(item)], self.sbox, key=int(item)) def set_value(self, value): if value is None: return b = "" n = 0 for ch in self._items: item = ch._setting_item v = value.get(int(item), None) if v is not None: b += str(item) + ": (" to_join = [] for c in ch._sub_items: sub_item = c._setting_sub_item try: sub_item_value = v[str(sub_item)] except KeyError: sub_item_value = c._control.get_value() c._control.set_value(sub_item_value) n += 1 to_join.append(str(sub_item) + f"={sub_item_value}") b += ", ".join(to_join) + ") " lbl_text = ngettext("%d value", "%d values", n) % n self._button.set_label(lbl_text) self._button.set_tooltip_text(b) class PackedRangeControl(MultipleRangeControl): def setup(self, setting): self._items = [] validator = setting._validator for item in range(validator.count): h = Gtk.HBox(homogeneous=False, spacing=0) lbl = Gtk.Label(label=str(validator.keys[item])) control = Gtk.Scale.new_with_range(Gtk.Orientation.HORIZONTAL, validator.min_value, validator.max_value, 1) control.set_round_digits(0) control.set_digits(0) control.connect("value-changed", self.changed, validator.keys[item]) h.pack_start(lbl, False, False, 0) h.pack_end(control, True, True, 0) h._setting_item = validator.keys[item] h.control = control lbl.set_margin_start(30) self.add(h) self._items.append(h) def changed(self, control, item): if control.get_sensitive(): if hasattr(control, "_timer"): control._timer.cancel() control._timer = Timer(0.5, lambda: GLib.idle_add(self._write, control, item)) control._timer.start() def _write(self, control, item): control._timer.cancel() delattr(control, "_timer") new_state = int(control.get_value()) if self.sbox.setting._value[int(item)] != new_state: self.sbox.setting._value[int(item)] = new_state _write_async(self.sbox.setting, self.sbox.setting._value[int(item)], self.sbox, key=int(item)) def set_value(self, value): if value is None: return b = "" n = len(self._items) for h in self._items: item = h._setting_item v = value.get(int(item), None) if v is not None: h.control.set_value(v) else: v = self.sbox.setting._value[int(item)] b += str(item) + ": (" + str(v) + ") " lbl_text = ngettext("%d value", "%d values", n) % n self._button.set_label(lbl_text) self._button.set_tooltip_text(b) # control with an ID key that determines what else to show class HeteroKeyControl(Gtk.HBox, Control): def __init__(self, sbox, delegate=None): super().__init__(homogeneous=False, spacing=6) self.init(sbox, delegate) self._items = {} for item in sbox.setting.possible_fields: if item["label"]: item_lblbox = Gtk.Label(label=item["label"]) self.pack_start(item_lblbox, False, False, 0) item_lblbox.set_visible(False) else: item_lblbox = None item_box = ComboBoxText() if item["kind"] == settings.KIND.choice: for entry in item["choices"]: item_box.append(str(int(entry)), str(entry)) item_box.set_active(0) item_box.connect("changed", self.changed) self.pack_start(item_box, False, False, 0) elif item["kind"] == settings.KIND.range: item_box = Scale() item_box.set_range(item["min"], item["max"]) item_box.set_round_digits(0) item_box.set_digits(0) item_box.set_increments(1, 5) item_box.connect("value-changed", self.changed) self.pack_start(item_box, True, True, 0) item_box.set_visible(False) self._items[str(item["name"])] = (item_lblbox, item_box) def get_value(self): result = {} for k, (_lblbox, box) in self._items.items(): result[str(k)] = box.get_value() result = hidpp20.LEDEffectSetting(**result) return result def set_value(self, value): self.set_sensitive(False) if value is not None: for k, v in value.__dict__.items(): if k in self._items: (lblbox, box) = self._items[k] box.set_value(v) else: self.sbox._failed.set_visible(True) self.setup_visibles(value.ID if value is not None else 0) def setup_visibles(self, id_): fields = self.sbox.setting.fields_map[id_][1] if id_ in self.sbox.setting.fields_map else {} for name, (lblbox, box) in self._items.items(): visible = name in fields or name == "ID" if lblbox: lblbox.set_visible(visible) box.set_visible(visible) def changed(self, control): if self.get_sensitive() and control.get_sensitive(): if "ID" in self._items and control == self._items["ID"][1]: self.setup_visibles(int(self._items["ID"][1].get_value())) if hasattr(control, "_timer"): control._timer.cancel() control._timer = Timer(0.3, lambda: GLib.idle_add(self._write, control)) control._timer.start() def _write(self, control): control._timer.cancel() delattr(control, "_timer") new_state = self.get_value() if self.sbox.setting._value != new_state: _write_async(self.sbox.setting, new_state, self.sbox) _allowables_icons = {True: "changes-allow", False: "changes-prevent", settings.SENSITIVITY_IGNORE: "dialog-error"} _allowables_tooltips = { True: _("Changes allowed"), False: _("No changes allowed"), settings.SENSITIVITY_IGNORE: _("Ignore this setting"), } _next_allowable = {True: False, False: settings.SENSITIVITY_IGNORE, settings.SENSITIVITY_IGNORE: True} _icons_allowables = {v: k for k, v in _allowables_icons.items()} # clicking on the lock icon changes from changeable to unchangeable to ignore def _change_click(button, sbox): icon = button.get_children()[0] icon_name, _ = icon.get_icon_name() allowed = _icons_allowables.get(icon_name, True) new_allowed = _next_allowable[allowed] sbox._control.set_sensitive(new_allowed is True) _change_icon(new_allowed, icon) if sbox.setting._device.persister: # remember the new setting sensitivity sbox.setting._device.persister.set_sensitivity(sbox.setting.name, new_allowed) if allowed == settings.SENSITIVITY_IGNORE: # update setting if it was being ignored setting = next((s for s in sbox.setting._device.settings if s.name == sbox.setting.name), None) if setting: persisted = sbox.setting._device.persister.get(setting.name) if sbox.setting._device.persister else None if setting.persist and persisted is not None: _write_async(setting, persisted, sbox) else: _read_async(setting, True, sbox, bool(sbox.setting._device.online), sbox._control.get_sensitive()) return True def _change_icon(allowed, icon): if allowed in _allowables_icons: icon._allowed = allowed icon.set_from_icon_name(_allowables_icons[allowed], Gtk.IconSize.LARGE_TOOLBAR) icon.set_tooltip_text(_allowables_tooltips[allowed]) def _create_sbox(s, _device): sbox = Gtk.HBox(homogeneous=False, spacing=6) sbox.setting = s sbox.kind = s.kind if s.description: sbox.set_tooltip_text(s.description) lbl = Gtk.Label(label=s.label) label = Gtk.EventBox() label.add(lbl) spinner = Gtk.Spinner() spinner.set_tooltip_text(_("Working") + "...") sbox._spinner = spinner failed = Gtk.Image.new_from_icon_name("dialog-warning", Gtk.IconSize.SMALL_TOOLBAR) failed.set_tooltip_text(_("Read/write operation failed.")) sbox._failed = failed change_icon = Gtk.Image.new_from_icon_name("changes-prevent", Gtk.IconSize.LARGE_TOOLBAR) sbox._change_icon = change_icon _change_icon(False, change_icon) change = Gtk.Button() change.set_relief(Gtk.ReliefStyle.NONE) change.add(change_icon) change.set_sensitive(True) change.connect("clicked", _change_click, sbox) if s.kind == settings.KIND.toggle: control = ToggleControl(sbox) elif s.kind == settings.KIND.range: control = SliderControl(sbox) elif s.kind == settings.KIND.choice: control = _create_choice_control(sbox) elif s.kind == settings.KIND.map_choice: control = MapChoiceControl(sbox) elif s.kind == settings.KIND.multiple_toggle: control = MultipleToggleControl(sbox, change) elif s.kind == settings.KIND.multiple_range: control = MultipleRangeControl(sbox, change) elif s.kind == settings.KIND.packed_range: control = PackedRangeControl(sbox, change) elif s.kind == settings.KIND.hetero: control = HeteroKeyControl(sbox, change) else: if logger.isEnabledFor(logging.WARNING): logger.warning("setting %s display not implemented", s.label) return None control.set_sensitive(False) # the first read will enable it control.layout(sbox, label, change, spinner, failed) sbox._control = control sbox.show_all() spinner.start() # the first read will stop it failed.set_visible(False) return sbox def _update_setting_item(sbox, value, is_online=True, sensitive=True, null_okay=False): sbox._spinner.stop() sensitive = sbox._change_icon._allowed if sensitive is None else sensitive if value is None and not null_okay: sbox._control.set_sensitive(sensitive is True) _change_icon(sensitive, sbox._change_icon) sbox._failed.set_visible(is_online) return sbox._failed.set_visible(False) sbox._control.set_sensitive(False) sbox._control.set_value(value) sbox._control.set_sensitive(sensitive is True) _change_icon(sensitive, sbox._change_icon) def _disable_listbox_highlight_bg(lb): colour = Gdk.RGBA() colour.parse("rgba(0,0,0,0)") for child in lb.get_children(): child.override_background_color(Gtk.StateFlags.PRELIGHT, colour) # config panel _box = None _items = {} def create(): global _box assert _box is None _box = Gtk.VBox(homogeneous=False, spacing=4) _box._last_device = None config_scroll = Gtk.ScrolledWindow() config_scroll.add(_box) config_scroll.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC) config_scroll.set_shadow_type(Gtk.ShadowType.NONE) # was IN config_scroll.set_size_request(0, 350) # ask for enough vertical space for about eight settings return config_scroll def update(device, is_online=None): assert _box is not None assert device device_id = (device.receiver.path if device.receiver else device.path, device.number) if is_online is None: is_online = bool(device.online) # if the device changed since last update, clear the box first if device_id != _box._last_device: _box.set_visible(False) _box._last_device = device_id # hide controls belonging to other devices for k, sbox in _items.items(): sbox = _items[k] sbox.set_visible(k[0:2] == device_id) for s in device.settings: k = (device_id[0], device_id[1], s.name) if k in _items: sbox = _items[k] else: sbox = _create_sbox(s, device) if sbox is None: continue _items[k] = sbox _box.pack_start(sbox, False, False, 0) sensitive = device.persister.get_sensitivity(s.name) if device.persister else True _read_async(s, False, sbox, is_online, sensitive) _box.set_visible(True) def clean(device): """Remove the controls for a given device serial. Needed after the device has been unpaired. """ assert _box is not None device_id = (device.receiver.path if device.receiver else device.path, device.number) for k in list(_items.keys()): if k[0:2] == device_id: _box.remove(_items[k]) del _items[k] def destroy(): global _box _box = None _items.clear() def change_setting(device, setting, values): """External interface to change a setting and have the GUI show the change""" assert device == setting._device GLib.idle_add(_change_setting, device, setting, values, priority=99) def _change_setting(device, setting, values): device_path = device.receiver.path if device.receiver else device.path if (device_path, device.number, setting.name) in _items: sbox = _items[(device_path, device.number, setting.name)] else: sbox = None _write_async(setting, values[-1], sbox, None, key=values[0] if len(values) > 1 else None) def record_setting(device, setting, values): """External interface to have the GUI show a change to a setting. Doesn't write to the device""" GLib.idle_add(_record_setting, device, setting, values, priority=99) def _record_setting(device, setting_class, values): if logger.isEnabledFor(logging.DEBUG): logger.debug("on %s changing setting %s to %s", device, setting_class.name, values) setting = next((s for s in device.settings if s.name == setting_class.name), None) if setting is None and logger.isEnabledFor(logging.DEBUG): logger.debug( "No setting for %s found on %s when trying to record a change made elsewhere", setting_class.name, device, ) if setting: assert device == setting._device if len(values) > 1: setting.update_key_value(values[0], values[-1]) value = {values[0]: values[-1]} else: setting.update(values[-1]) value = values[-1] device_path = device.receiver.path if device.receiver else device.path if (device_path, device.number, setting.name) in _items: sbox = _items[(device_path, device.number, setting.name)] if sbox: _update_setting_item(sbox, value, sensitive=None)
32,129
Python
.py
711
35.694796
119
0.613548
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,484
rule_base.py
pwr-Solaar_Solaar/lib/solaar/ui/rule_base.py
## Copyright (C) Solaar Contributors ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from contextlib import contextmanager as contextlib_contextmanager from typing import Callable from gi.repository import Gtk from logitech_receiver import diversion def norm(s): return s.replace("_", "").replace(" ", "").lower() class CompletionEntry(Gtk.Entry): def __init__(self, values, *args, **kwargs): super().__init__(*args, **kwargs) CompletionEntry.add_completion_to_entry(self, values) @classmethod def add_completion_to_entry(cls, entry, values): completion = entry.get_completion() if not completion: liststore = Gtk.ListStore(str) completion = Gtk.EntryCompletion() completion.set_model(liststore) completion.set_match_func(lambda completion, key, it: norm(key) in norm(completion.get_model()[it][0])) completion.set_text_column(0) entry.set_completion(completion) else: liststore = completion.get_model() liststore.clear() for v in sorted(set(values), key=str.casefold): liststore.append((v,)) class RuleComponentUI: CLASS = diversion.RuleComponent def __init__(self, panel, on_update: Callable = None): self.panel = panel self.widgets = {} # widget -> coord. in grid self.component = None self._ignore_changes = 0 self._on_update_callback = (lambda: None) if on_update is None else on_update self.create_widgets() def create_widgets(self): pass def show(self, component, editable=True): self._show_widgets(editable) self.component = component def collect_value(self): return None @contextlib_contextmanager def ignore_changes(self): self._ignore_changes += 1 yield None self._ignore_changes -= 1 def _on_update(self, *_args): if not self._ignore_changes and self.component is not None: value = self.collect_value() self.component.__init__(value, warn=False) self._on_update_callback() return value return None def _show_widgets(self, editable): self._remove_panel_items() for widget, coord in self.widgets.items(): self.panel.attach(widget, *coord) widget.set_sensitive(editable) widget.show() @classmethod def left_label(cls, component) -> str: return type(component).__name__ @classmethod def right_label(cls, _component) -> str: return "" @classmethod def icon_name(cls) -> str: return "" def _remove_panel_items(self): for c in self.panel.get_children(): self.panel.remove(c) def update_devices(self): pass
3,517
Python
.py
88
32.909091
115
0.658744
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,485
desktop_notifications.py
pwr-Solaar_Solaar/lib/solaar/ui/desktop_notifications.py
## Copyright (C) 2012-2013 Daniel Pavel ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import importlib # Optional desktop notifications. import logging from solaar import NAME from solaar.i18n import _ from . import icons logger = logging.getLogger(__name__) def notifications_available(): """Checks if notification service is available.""" notifications_supported = False try: import gi gi.require_version("Notify", "0.7") importlib.util.find_spec("gi.repository.GLib") importlib.util.find_spec("gi.repository.Notify") notifications_supported = True except ValueError as e: logger.warning(f"Notification service is not available: {e}") return notifications_supported available = notifications_available() if available: from gi.repository import GLib from gi.repository import Notify # cache references to shown notifications here, so if another status comes # while its notification is still visible we don't create another one _notifications = {} def init(): """Initialize desktop notifications.""" global available if available: if not Notify.is_initted(): if logger.isEnabledFor(logging.INFO): logger.info("starting desktop notifications") try: return Notify.init(NAME.lower()) except Exception: logger.exception("initializing desktop notifications") available = False return available and Notify.is_initted() def uninit(): """Stop desktop notifications.""" if available and Notify.is_initted(): if logger.isEnabledFor(logging.INFO): logger.info("stopping desktop notifications") _notifications.clear() Notify.uninit() def alert(reason, icon=None): assert reason if available and Notify.is_initted(): n = _notifications.get(NAME.lower()) if n is None: n = _notifications[NAME.lower()] = Notify.Notification() # we need to use the filename here because the notifications daemon # is an external application that does not know about our icon sets icon_file = icons.icon_file(NAME.lower()) if icon is None else icons.icon_file(icon) n.update(NAME.lower(), reason, icon_file) n.set_urgency(Notify.Urgency.NORMAL) n.set_hint("desktop-entry", GLib.Variant("s", NAME.lower())) try: n.show() except Exception: logger.exception("showing %s", n) def show(dev, reason=None, icon=None, progress=None): """Show a notification with title and text. Optionally displays the `progress` integer value in [0, 100] as a progress bar.""" if available and Notify.is_initted(): summary = dev.name # if a notification with same name is already visible, reuse it to avoid spamming n = _notifications.get(summary) if n is None: n = _notifications[summary] = Notify.Notification() if reason: message = reason else: message = _("unspecified reason") # we need to use the filename here because the notifications daemon # is an external application that does not know about our icon sets icon_file = icons.device_icon_file(dev.name, dev.kind) if icon is None else icons.icon_file(icon) n.update(summary, message, icon_file) n.set_urgency(Notify.Urgency.NORMAL) n.set_hint("desktop-entry", GLib.Variant("s", NAME.lower())) if progress: n.set_hint("value", GLib.Variant("i", progress)) try: n.show() except Exception: logger.exception(f"showing {n}") else: def init(): return False def uninit(): return None # toggle = lambda action: False def alert(reason): return None def show(dev, reason=None): return None
4,877
Python
.py
113
34.026549
109
0.638073
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,486
tray.py
pwr-Solaar_Solaar/lib/solaar/ui/tray.py
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/ ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import logging import os from time import time import gi from gi.repository import GLib from gi.repository import Gtk from gi.repository.Gdk import ScrollDirection import solaar.gtk as gtk from solaar import NAME from solaar.i18n import _ from . import action from . import icons from . import window from .about import about logger = logging.getLogger(__name__) _TRAY_ICON_SIZE = 48 _MENU_ICON_SIZE = Gtk.IconSize.LARGE_TOOLBAR def _create_menu(quit_handler): # per-device menu entries will be generated as-needed menu = Gtk.Menu() no_receiver = Gtk.MenuItem.new_with_label(_("No supported device found")) no_receiver.set_sensitive(False) menu.append(no_receiver) menu.append(Gtk.SeparatorMenuItem.new()) menu.append(action.make_image_menu_item(_("About %s") % NAME, "help-about", about.show)) menu.append(action.make_image_menu_item(_("Quit %s") % NAME, "application-exit", quit_handler)) menu.show_all() return menu _last_scroll = 0 def _scroll(tray_icon, event, direction=None): if direction is None: direction = event.direction now = event.time / 1000.0 else: now = None if direction != ScrollDirection.UP and direction != ScrollDirection.DOWN: # ignore all other directions return # don't bother even trying to scroll if less than two devices if sum(map(lambda i: i[1] is not None, _devices_info)) < 2: return # scroll events come way too fast (at least 5-6 at once) so take a little break between them global _last_scroll now = now or time() if now - _last_scroll < 0.33: # seconds return _last_scroll = now global _picked_device candidate = None if _picked_device is None: for info in _devices_info: # pick first peripheral found if info[1] is not None: candidate = info break else: found = False for info in _devices_info: if not info[1]: # only conside peripherals continue # compare peripherals if info[0:2] == _picked_device[0:2]: if direction == ScrollDirection.UP and candidate: # select previous device break found = True else: if found: candidate = info if direction == ScrollDirection.DOWN: break # if direction is up, but no candidate found before _picked, # let it run through all candidates, will get stuck with the last one else: if direction == ScrollDirection.DOWN: # only use the first one, in case no candidates are after _picked if candidate is None: candidate = info else: candidate = info # if the last _picked_device is gone, clear it # the candidate will be either the first or last one remaining, # depending on the scroll direction if not found: _picked_device = None _picked_device = candidate or _picked_device if logger.isEnabledFor(logging.DEBUG): logger.debug("scroll: picked %s", _picked_device) _update_tray_icon() try: try: gi.require_version("AyatanaAppIndicator3", "0.1") from gi.repository import AyatanaAppIndicator3 as AppIndicator3 ayatana_appindicator_found = True except ValueError: try: gi.require_version("AppIndicator3", "0.1") from gi.repository import AppIndicator3 ayatana_appindicator_found = False except ValueError as exc: # treat unavailable versions the same as unavailable packages raise ImportError from exc if logger.isEnabledFor(logging.DEBUG): logger.debug(f"using {'Ayatana ' if ayatana_appindicator_found else ''}AppIndicator3") # Defense against AppIndicator3 bug that treats files in current directory as icon files # https://bugs.launchpad.net/ubuntu/+source/libappindicator/+bug/1363277 # Defense against bug that shows up in XFCE 4.16 where icons are not upscaled def _icon_file(icon_name): if gtk.tray_icon_size is None and not os.path.isfile(icon_name): return icon_name icon_info = Gtk.IconTheme.get_default().lookup_icon( icon_name, gtk.tray_icon_size or _TRAY_ICON_SIZE, Gtk.IconLookupFlags.FORCE_SVG ) return icon_info.get_filename() if icon_info else icon_name def _create(menu): icons._init_icon_paths() ind = AppIndicator3.Indicator.new( "indicator-solaar", _icon_file(icons.TRAY_INIT), AppIndicator3.IndicatorCategory.HARDWARE ) ind.set_title(NAME) ind.set_status(AppIndicator3.IndicatorStatus.ACTIVE) # ind.set_attention_icon_full(_icon_file(icons.TRAY_ATTENTION), '') # works poorly for XFCE 16 # ind.set_label(NAME.lower(), NAME.lower()) ind.set_menu(menu) ind.connect("scroll-event", _scroll) return ind def _hide(indicator): indicator.set_status(AppIndicator3.IndicatorStatus.PASSIVE) def _show(indicator): indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE) def _update_tray_icon(): if _picked_device and gtk.battery_icons_style != "solaar": _ignore, _ignore, name, device = _picked_device battery_level = device.battery_info.level if device.battery_info is not None else None battery_charging = device.battery_info.charging() if device.battery_info is not None else None tray_icon_name = icons.battery(battery_level, battery_charging) description = f"{name}: {device.status_string()}" else: # there may be a receiver, but no peripherals tray_icon_name = icons.TRAY_OKAY if _devices_info else icons.TRAY_INIT description_lines = _generate_description_lines() description = "\n".join(description_lines).rstrip("\n") # icon_file = icons.icon_file(icon_name, _TRAY_ICON_SIZE) _icon.set_icon_full(_icon_file(tray_icon_name), description) def attention(reason=None): if _icon.get_status() != AppIndicator3.IndicatorStatus.ATTENTION: # _icon.set_attention_icon_full(_icon_file(icons.TRAY_ATTENTION), reason or '') # works poorly for XFCe 16 _icon.set_status(AppIndicator3.IndicatorStatus.ATTENTION) GLib.timeout_add(10 * 1000, _icon.set_status, AppIndicator3.IndicatorStatus.ACTIVE) except ImportError: if logger.isEnabledFor(logging.DEBUG): logger.debug("using StatusIcon") def _create(menu): icon = Gtk.StatusIcon.new_from_icon_name(icons.TRAY_INIT) icon.set_name(NAME.lower()) icon.set_title(NAME) icon.set_tooltip_text(NAME) icon.connect("activate", window.toggle) icon.connect("scroll-event", _scroll) icon.connect( "popup-menu", lambda icon, button, time: menu.popup(None, None, icon.position_menu, icon, button, time), ) return icon def _hide(icon): icon.set_visible(False) def _show(icon): icon.set_visible(True) def _update_tray_icon(): tooltip_lines = _generate_tooltip_lines() tooltip = "\n".join(tooltip_lines).rstrip("\n") _icon.set_tooltip_markup(tooltip) if _picked_device and gtk.battery_icons_style != "solaar": _ignore, _ignore, name, device = _picked_device battery_level = device.battery_info.level if device.battery_info is not None else None battery_charging = device.battery_info.charging() if device.battery_info is not None else None tray_icon_name = icons.battery(battery_level, battery_charging) else: # there may be a receiver, but no peripherals tray_icon_name = icons.TRAY_OKAY if _devices_info else icons.TRAY_ATTENTION _icon.set_from_icon_name(tray_icon_name) _icon_before_attention = None def _blink(count): global _icon_before_attention if count % 2: _icon.set_from_icon_name(icons.TRAY_ATTENTION) else: _icon.set_from_icon_name(_icon_before_attention) if count > 0: GLib.timeout_add(1000, _blink, count - 1) else: _icon_before_attention = None def attention(reason=None): global _icon_before_attention if _icon_before_attention is None: _icon_before_attention = _icon.get_icon_name() GLib.idle_add(_blink, 9) def _generate_tooltip_lines(): if not _devices_info: yield f"<b>{NAME}</b>: " + _("no receiver") return yield from _generate_description_lines() def _generate_description_lines(): if not _devices_info: yield _("no receiver") return for _ignore, number, name, device in _devices_info: if number is None: # receiver continue p = device.status_string() if p: # does it have any properties to print? yield f"<b>{name}</b>" if device.online: yield f"\t{p}" else: yield f"\t{p} <small>(" + _("offline") + ")</small>" else: if device.online: yield f"<b>{name}</b> <small>(" + _("no status") + ")</small>" else: yield f"<b>{name}</b> <small>(" + _("offline") + ")</small>" def _pick_device_with_lowest_battery(): if not _devices_info: return None picked = None picked_level = 1000 for info in _devices_info: if info[1] is None: # is receiver continue level = info[-1].battery_info.level if info[-1].battery_info is not None else None if level is not None and picked_level > level: picked = info picked_level = level or 0 if logger.isEnabledFor(logging.DEBUG): logger.debug("picked device with lowest battery: %s", picked) return picked def _add_device(device): assert device index = 0 receiver_path = device.receiver.path if device.receiver is not None else device.path if device.receiver is not None: # if receiver insert into devices for the receiver in device number order for idx, (path, _ignore, _ignore, _ignore) in enumerate(_devices_info): if path and path == receiver_path: index = idx + 1 # the first entry matching the receiver serial should be for the receiver itself break while index < len(_devices_info): path, number, _ignore, _ignore = _devices_info[index] if not path == receiver_path: break assert number != device.number if number > device.number: break index = index + 1 new_device_info = (receiver_path, device.number, device.name, device) _devices_info.insert(index, new_device_info) label = (" " if device.number else "") + device.name new_menu_item = action.make_image_menu_item(label, None, window.popup, receiver_path, device.number) _menu.insert(new_menu_item, index) return index def _remove_device(index): assert index is not None menu_items = _menu.get_children() _menu.remove(menu_items[index]) removed_device = _devices_info.pop(index) global _picked_device if _picked_device and _picked_device[0:2] == removed_device[0:2]: # the current pick was unpaired _picked_device = None def _add_receiver(receiver): index = len(_devices_info) new_receiver_info = (receiver.path, None, receiver.name, None) _devices_info.insert(index, new_receiver_info) icon_name = icons.device_icon_name(receiver.name, receiver.kind) new_menu_item = action.make_image_menu_item(receiver.name, icon_name, window.popup, receiver.path) _menu.insert(new_menu_item, index) return 0 def _remove_receiver(receiver): index = 0 # remove all entries in devices_info that match this receiver while index < len(_devices_info): path, _ignore, _ignore, _ignore = _devices_info[index] if path == receiver.path: _remove_device(index) else: index += 1 def _update_menu_item(index, device): if device is None: logger.warning("updating an inactive device %s, assuming disconnected", device) return None menu_items = _menu.get_children() menu_item = menu_items[index] level = device.battery_info.level if device.battery_info is not None else None charging = device.battery_info.charging() if device.battery_info is not None else None icon_name = icons.battery(level, charging) menu_item.label.set_label((" " if 0 < device.number <= 6 else "") + device.name + ": " + device.status_string()) image_widget = menu_item.icon image_widget.set_sensitive(bool(device.online)) image_widget.set_from_icon_name(icon_name, _MENU_ICON_SIZE) # for which device to show the battery info in systray, if more than one # it's actually an entry in _devices_info _picked_device = None # cached list of devices and some of their properties # contains tuples of (receiver path, device number, name, device) _devices_info = [] _menu = None _icon = None def init(_quit_handler): global _menu, _icon assert _menu is None _menu = _create_menu(_quit_handler) assert _icon is None _icon = _create(_menu) update() def destroy(): global _icon, _menu, _devices_info if _icon is not None: i, _icon = _icon, None _hide(i) i = None _icon = None _menu = None _devices_info = None def update(device=None): if _icon is None: return if device is not None: if device.kind is None: # receiver is_alive = bool(device) receiver_path = device.path if is_alive: index = None for idx, (path, _ignore, _ignore, _ignore) in enumerate(_devices_info): if path == receiver_path: index = idx break if index is None: _add_receiver(device) else: _remove_receiver(device) else: # peripheral is_paired = bool(device) receiver_path = device.receiver.path if device.receiver is not None else device.path index = None for idx, (path, number, _ignore, _ignore) in enumerate(_devices_info): if path == receiver_path and number == device.number: index = idx if is_paired: if index is None: index = _add_device(device) _update_menu_item(index, device) else: # was just unpaired or unplugged if index is not None: _remove_device(index) menu_items = _menu.get_children() no_receivers_index = len(_devices_info) menu_items[no_receivers_index].set_visible(not _devices_info) global _picked_device if (not _picked_device or _last_scroll == 0) and device is not None and device.kind is not None: # if it's just a receiver update, it's unlikely the picked device would change _picked_device = _pick_device_with_lowest_battery() _update_tray_icon() if _icon: if not _devices_info: _hide(_icon) else: _show(_icon)
16,646
Python
.py
385
34.353247
118
0.630491
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,487
__init__.py
pwr-Solaar_Solaar/lib/solaar/ui/__init__.py
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/ ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import logging from typing import Callable import gi import yaml from logitech_receiver.common import Alert from solaar.i18n import _ from solaar.ui.config_panel import change_setting from solaar.ui.config_panel import record_setting from solaar.ui.window import find_device from . import common from . import desktop_notifications from . import diversion_rules from . import tray from . import window gi.require_version("Gtk", "3.0") from gi.repository import Gio # NOQA: E402 from gi.repository import GLib # NOQA: E402 from gi.repository import Gtk # NOQA: E402 logger = logging.getLogger(__name__) assert Gtk.get_major_version() > 2, "Solaar requires Gtk 3 python bindings" APP_ID = "io.github.pwr_solaar.solaar" def _startup(app, startup_hook, use_tray, show_window): if logger.isEnabledFor(logging.DEBUG): logger.debug("startup registered=%s, remote=%s", app.get_is_registered(), app.get_is_remote()) common.start_async() desktop_notifications.init() if use_tray: tray.init(lambda _ignore: window.destroy()) window.init(show_window, use_tray) startup_hook() def _activate(app): if logger.isEnabledFor(logging.DEBUG): logger.debug("activate") if app.get_windows(): window.popup() else: app.add_window(window._window) def _command_line(app, command_line): args = command_line.get_arguments() args = yaml.safe_load("".join(args)) if args else args if not args: _activate(app) elif args[0] == "config": # config call from remote instance if logger.isEnabledFor(logging.INFO): logger.info("remote command line %s", args) dev = find_device(args[1]) if dev: setting = next((s for s in dev.settings if s.name == args[2]), None) if setting: change_setting(dev, setting, args[3:]) return 0 def _shutdown(_app, shutdown_hook): if logger.isEnabledFor(logging.DEBUG): logger.debug("shutdown") shutdown_hook() common.stop_async() tray.destroy() desktop_notifications.uninit() def run_loop( startup_hook: Callable[[], None], shutdown_hook: Callable[[], None], use_tray: bool, show_window: bool, ): assert use_tray or show_window, "need either tray or visible window" application = Gtk.Application.new(APP_ID, Gio.ApplicationFlags.HANDLES_COMMAND_LINE) application.connect( "startup", lambda app, startup_hook: _startup(app, startup_hook, use_tray, show_window), startup_hook, ) application.connect("command-line", _command_line) application.connect("activate", _activate) application.connect("shutdown", _shutdown, shutdown_hook) application.register() if application.get_is_remote(): print(_("Another Solaar process is already running so just expose its window")) application.run() def _status_changed(device, alert, reason, refresh=False): assert device is not None if logger.isEnabledFor(logging.DEBUG): logger.debug("status changed: %s (%s) %s", device, alert, reason) if alert is None: alert = Alert.NONE tray.update(device) if alert & Alert.ATTENTION: tray.attention(reason) need_popup = alert & Alert.SHOW_WINDOW window.update(device, need_popup, refresh) diversion_rules.update_devices() if alert & (Alert.NOTIFICATION | Alert.ATTENTION): desktop_notifications.show(device, reason) def status_changed(device, alert=Alert.NONE, reason=None, refresh=False): GLib.idle_add(_status_changed, device, alert, reason, refresh) def setting_changed(device, setting_class, vals): record_setting(device, setting_class, vals)
4,567
Python
.py
112
36.160714
102
0.714156
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,488
diversion_rules.py
pwr-Solaar_Solaar/lib/solaar/ui/diversion_rules.py
## Copyright (C) Solaar Contributors ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from __future__ import annotations import dataclasses import logging import string import threading from collections import defaultdict from copy import copy from dataclasses import dataclass from dataclasses import field from enum import Enum from shlex import quote as shlex_quote from typing import Any from typing import Callable from typing import Dict from typing import Optional from gi.repository import Gdk from gi.repository import GObject from gi.repository import Gtk from logitech_receiver import diversion as _DIV from logitech_receiver.common import NamedInt from logitech_receiver.common import NamedInts from logitech_receiver.common import UnsortedNamedInts from logitech_receiver.settings import KIND as _SKIND from logitech_receiver.settings import Setting from logitech_receiver.settings_templates import SETTINGS from solaar.i18n import _ from solaar.ui import rule_actions from solaar.ui import rule_conditions from solaar.ui.rule_base import RuleComponentUI from solaar.ui.rule_base import norm from solaar.ui.rule_conditions import ConditionUI logger = logging.getLogger(__name__) _diversion_dialog = None _rule_component_clipboard = None class RuleComponentWrapper(GObject.GObject): def __init__(self, component, level=0, editable=False): self.component = component self.level = level self.editable = editable GObject.GObject.__init__(self) def display_left(self): if isinstance(self.component, _DIV.Rule): if self.level == 0: return _("Built-in rules") if not self.editable else _("User-defined rules") if self.level == 1: return " " + _("Rule") return " " + _("Sub-rule") if self.component is None: return _("[empty]") return " " + self.__component_ui().left_label(self.component) def display_right(self): if self.component is None: return "" return self.__component_ui().right_label(self.component) def display_icon(self): if self.component is None: return "" if isinstance(self.component, _DIV.Rule) and self.level == 0: return "emblem-system" if not self.editable else "avatar-default" return self.__component_ui().icon_name() def __component_ui(self): return COMPONENT_UI.get(type(self.component), UnsupportedRuleComponentUI) def _create_close_dialog(window: Gtk.Window) -> Gtk.MessageDialog: """Creates rule editor close dialog, when unsaved changes are present.""" dialog = Gtk.MessageDialog( window, type=Gtk.MessageType.QUESTION, title=_("Make changes permanent?"), flags=Gtk.DialogFlags.MODAL, ) dialog.set_default_size(400, 100) dialog.add_buttons( _("Yes"), Gtk.ResponseType.YES, _("No"), Gtk.ResponseType.NO, _("Cancel"), Gtk.ResponseType.CANCEL, ) dialog.set_markup(_("If you choose No, changes will be lost when Solaar is closed.")) return dialog def _create_selected_rule_edit_panel() -> Gtk.Grid: """Creates the edit Condition/Actions panel for a rule. Shows the UI for the selected rule component. """ grid = Gtk.Grid() grid.set_margin_start(10) grid.set_margin_end(10) grid.set_row_spacing(10) grid.set_column_spacing(10) grid.set_halign(Gtk.Align.CENTER) grid.set_valign(Gtk.Align.CENTER) grid.set_size_request(0, 120) return grid def _populate_model( model: Gtk.TreeStore, it: Gtk.TreeIter, rule_component: Any, level: int = 0, pos: int = -1, editable: Optional[bool] = None, ): if isinstance(rule_component, list): for c in rule_component: _populate_model(model, it, c, level=level, pos=pos, editable=editable) if pos >= 0: pos += 1 return if editable is None: editable = model[it][0].editable if it is not None else False if isinstance(rule_component, _DIV.Rule): editable = editable or (rule_component.source is not None) wrapped = RuleComponentWrapper(rule_component, level, editable=editable) piter = model.insert(it, pos, (wrapped,)) if isinstance(rule_component, (_DIV.Rule, _DIV.And, _DIV.Or, _DIV.Later)): for c in rule_component.components: ed = editable or (isinstance(c, _DIV.Rule) and c.source is not None) _populate_model(model, piter, c, level + 1, editable=ed) if len(rule_component.components) == 0: _populate_model(model, piter, None, level + 1, editable=editable) elif isinstance(rule_component, _DIV.Not): _populate_model(model, piter, rule_component.component, level + 1, editable=editable) @dataclasses.dataclass class AllowedActions: c: Any copy: bool delete: bool flatten: bool insert: bool insert_only_rule: bool insert_root: bool wrap: bool def allowed_actions(m: Gtk.TreeStore, it: Gtk.TreeIter) -> AllowedActions: row = m[it] wrapped = row[0] c = wrapped.component parent_it = m.iter_parent(it) parent_c = m[parent_it][0].component if wrapped.level > 0 else None can_wrap = wrapped.editable and wrapped.component is not None and wrapped.level >= 2 can_delete = wrapped.editable and not isinstance(parent_c, _DIV.Not) and c is not None and wrapped.level >= 1 can_insert = wrapped.editable and not isinstance(parent_c, _DIV.Not) and wrapped.level >= 2 can_insert_only_rule = wrapped.editable and wrapped.level == 1 can_flatten = ( wrapped.editable and not isinstance(parent_c, _DIV.Not) and isinstance(c, (_DIV.Rule, _DIV.And, _DIV.Or)) and wrapped.level >= 2 and len(c.components) ) can_copy = wrapped.level >= 1 can_insert_root = wrapped.editable and wrapped.level == 0 return AllowedActions( c, can_copy, can_delete, can_flatten, can_insert, can_insert_only_rule, can_insert_root, can_wrap, ) class ActionMenu: def __init__( self, window: Gtk.Window, tree_view: Gtk.TreeView, populate_model_func: Callable, on_update: Callable, ): self.window = window self.tree_view = tree_view self._populate_model_func = populate_model_func self._on_update = on_update def create_menu_event_button_released(self, v, e): if e.button == Gdk.BUTTON_SECONDARY: # right click menu = Gtk.Menu() m, it = v.get_selection().get_selected() enabled_actions = allowed_actions(m, it) for item in self.get_insert_menus(m, it, enabled_actions): menu.append(item) if enabled_actions.flatten: menu.append(self._menu_flatten(m, it)) if enabled_actions.wrap: menu.append(self._menu_wrap(m, it)) menu.append(self._menu_negate(m, it)) if menu.get_children(): menu.append(Gtk.SeparatorMenuItem(visible=True)) if enabled_actions.delete: menu.append(self._menu_cut(m, it)) if enabled_actions.copy and enabled_actions.c is not None: menu.append(self._menu_copy(m, it)) if enabled_actions.insert and _rule_component_clipboard is not None: p = self._menu_paste(m, it) menu.append(p) if enabled_actions.c is None: # just a placeholder p.set_label(_("Paste here")) else: p.set_label(_("Paste above")) p2 = self._menu_paste(m, it, below=True) p2.set_label(_("Paste below")) menu.append(p2) elif enabled_actions.insert_only_rule and isinstance(_rule_component_clipboard, _DIV.Rule): p = self._menu_paste(m, it) menu.append(p) if enabled_actions.c is None: p.set_label(_("Paste rule here")) else: p.set_label(_("Paste rule above")) p2 = self._menu_paste(m, it, below=True) p2.set_label(_("Paste rule below")) menu.append(p2) elif enabled_actions.insert_root and isinstance(_rule_component_clipboard, _DIV.Rule): p = self._menu_paste(m, m.iter_nth_child(it, 0)) p.set_label(_("Paste rule")) menu.append(p) if menu.get_children() and enabled_actions.delete: menu.append(Gtk.SeparatorMenuItem(visible=True)) if enabled_actions.delete: menu.append(self._menu_delete(m, it)) if menu.get_children(): menu.popup_at_pointer(e) def get_insert_menus(self, m, it, enabled_actions: AllowedActions): items = [] if enabled_actions.insert: ins = self._menu_insert(m, it) items.append(ins) if enabled_actions.c is None: # just a placeholder ins.set_label(_("Insert here")) else: ins.set_label(_("Insert above")) ins2 = self._menu_insert(m, it, below=True) ins2.set_label(_("Insert below")) items.append(ins2) elif enabled_actions.insert_only_rule: ins = self._menu_create_rule(m, it) items.append(ins) if enabled_actions.c is None: ins.set_label(_("Insert new rule here")) else: ins.set_label(_("Insert new rule above")) ins2 = self._menu_create_rule(m, it, below=True) ins2.set_label(_("Insert new rule below")) items.append(ins2) elif enabled_actions.insert_root: ins = self._menu_create_rule(m, m.iter_nth_child(it, 0)) items.append(ins) return items def menu_do_flatten(self, _mitem, m, it): wrapped = m[it][0] c = wrapped.component parent_it = m.iter_parent(it) parent_c = m[parent_it][0].component idx = parent_c.components.index(c) if isinstance(c, _DIV.Not): parent_c.components = [*parent_c.components[:idx], c.component, *parent_c.components[idx + 1 :]] children = [next(m[it].iterchildren())[0].component] else: parent_c.components = [*parent_c.components[:idx], *c.components, *parent_c.components[idx + 1 :]] children = [child[0].component for child in m[it].iterchildren()] m.remove(it) self._populate_model_func(m, parent_it, children, level=wrapped.level, pos=idx) new_iter = m.iter_nth_child(parent_it, idx) self.tree_view.expand_row(m.get_path(parent_it), True) self.tree_view.get_selection().select_iter(new_iter) self._on_update() def _menu_flatten(self, m, it): menu_flatten = Gtk.MenuItem(_("Flatten")) menu_flatten.connect("activate", self.menu_do_flatten, m, it) menu_flatten.show() return menu_flatten def _menu_do_insert(self, _mitem, m, it, new_c, below=False): wrapped = m[it][0] c = wrapped.component parent_it = m.iter_parent(it) parent_c = m[parent_it][0].component if len(parent_c.components) == 0: # we had only a placeholder idx = 0 else: idx = parent_c.components.index(c) if isinstance(new_c, _DIV.Rule) and wrapped.level == 1: new_c.source = _DIV._file_path # new rules will be saved to the YAML file idx += int(below) parent_c.components.insert(idx, new_c) self._populate_model_func(m, parent_it, new_c, level=wrapped.level, pos=idx) self._on_update() if len(parent_c.components) == 1: m.remove(it) # remove placeholder in the end new_iter = m.iter_nth_child(parent_it, idx) self.tree_view.get_selection().select_iter(new_iter) if isinstance(new_c, (_DIV.Rule, _DIV.And, _DIV.Or, _DIV.Not)): self.tree_view.expand_row(m.get_path(new_iter), True) def _menu_do_insert_new(self, _mitem, m, it, cls, initial_value, below=False): new_c = cls(initial_value, warn=False) return self._menu_do_insert(_mitem, m, it, new_c, below=below) def _menu_insert(self, m, it, below=False): elements = [ _("Insert"), [ (_("Sub-rule"), _DIV.Rule, []), (_("Or"), _DIV.Or, []), (_("And"), _DIV.And, []), [ _("Condition"), [ (_("Feature"), _DIV.Feature, rule_conditions.FeatureUI.FEATURES_WITH_DIVERSION[0]), (_("Report"), _DIV.Report, 0), (_("Process"), _DIV.Process, ""), (_("Mouse process"), _DIV.MouseProcess, ""), (_("Modifiers"), _DIV.Modifiers, []), (_("Key"), _DIV.Key, ""), (_("KeyIsDown"), _DIV.KeyIsDown, ""), (_("Active"), _DIV.Active, ""), (_("Device"), _DIV.Device, ""), (_("Host"), _DIV.Host, ""), (_("Setting"), _DIV.Setting, [None, "", None]), (_("Test"), _DIV.Test, next(iter(_DIV.TESTS))), (_("Test bytes"), _DIV.TestBytes, [0, 1, 0]), (_("Mouse Gesture"), _DIV.MouseGesture, ""), ], ], [ _("Action"), [ (_("Key press"), _DIV.KeyPress, "space"), (_("Mouse scroll"), _DIV.MouseScroll, [0, 0]), (_("Mouse click"), _DIV.MouseClick, ["left", 1]), (_("Set"), _DIV.Set, [None, "", None]), (_("Execute"), _DIV.Execute, [""]), (_("Later"), _DIV.Later, [1]), ], ], ], ] def build(spec): if isinstance(spec, list): # has sub-menu label, children = spec item = Gtk.MenuItem(label) submenu = Gtk.Menu() item.set_submenu(submenu) for child in children: submenu.append(build(child)) return item elif isinstance(spec, tuple): # has click action label, feature, *args = spec item = Gtk.MenuItem(label) args = [a.copy() if isinstance(a, list) else a for a in args] item.connect("activate", self._menu_do_insert_new, m, it, feature, *args, below) return item else: return None menu_insert = build(elements) menu_insert.show_all() return menu_insert def _menu_create_rule(self, m, it, below=False) -> Gtk.MenuItem: menu_create_rule = Gtk.MenuItem(_("Insert new rule")) menu_create_rule.connect("activate", self._menu_do_insert_new, m, it, _DIV.Rule, [], below) menu_create_rule.show() return menu_create_rule def menu_do_delete(self, _mitem, m, it): wrapped = m[it][0] c = wrapped.component parent_it = m.iter_parent(it) parent_c = m[parent_it][0].component idx = parent_c.components.index(c) parent_c.components.pop(idx) if len(parent_c.components) == 0: # placeholder self._populate_model_func(m, parent_it, None, level=wrapped.level) m.remove(it) self.tree_view.get_selection().select_iter(m.iter_nth_child(parent_it, max(0, min(idx, len(parent_c.components) - 1)))) self._on_update() return c def _menu_delete(self, m, it) -> Gtk.MenuItem: menu_delete = Gtk.MenuItem(_("Delete")) menu_delete.connect("activate", self.menu_do_delete, m, it) menu_delete.show() return menu_delete def menu_do_negate(self, _mitem, m, it): wrapped = m[it][0] c = wrapped.component parent_it = m.iter_parent(it) parent_c = m[parent_it][0].component if isinstance(c, _DIV.Not): # avoid double negation self.menu_do_flatten(_mitem, m, it) self.tree_view.expand_row(m.get_path(parent_it), True) elif isinstance(parent_c, _DIV.Not): # avoid double negation self.menu_do_flatten(_mitem, m, parent_it) else: idx = parent_c.components.index(c) self._menu_do_insert_new(_mitem, m, it, _DIV.Not, c, below=True) self.menu_do_delete(_mitem, m, m.iter_nth_child(parent_it, idx)) self._on_update() def _menu_negate(self, m, it) -> Gtk.MenuItem: menu_negate = Gtk.MenuItem(_("Negate")) menu_negate.connect("activate", self.menu_do_negate, m, it) menu_negate.show() return menu_negate def menu_do_wrap(self, _mitem, m, it, cls): wrapped = m[it][0] c = wrapped.component parent_it = m.iter_parent(it) parent_c = m[parent_it][0].component if isinstance(parent_c, _DIV.Not): new_c = cls([c], warn=False) parent_c.component = new_c m.remove(it) self._populate_model_func(m, parent_it, new_c, level=wrapped.level, pos=0) self.tree_view.expand_row(m.get_path(parent_it), True) self.tree_view.get_selection().select_iter(m.iter_nth_child(parent_it, 0)) else: idx = parent_c.components.index(c) self._menu_do_insert_new(_mitem, m, it, cls, [c], below=True) self.menu_do_delete(_mitem, m, m.iter_nth_child(parent_it, idx)) self._on_update() def _menu_wrap(self, m, it) -> Gtk.MenuItem: menu_wrap = Gtk.MenuItem(_("Wrap with")) submenu_wrap = Gtk.Menu() menu_sub_rule = Gtk.MenuItem(_("Sub-rule")) menu_and = Gtk.MenuItem(_("And")) menu_or = Gtk.MenuItem(_("Or")) menu_sub_rule.connect("activate", self.menu_do_wrap, m, it, _DIV.Rule) menu_and.connect("activate", self.menu_do_wrap, m, it, _DIV.And) menu_or.connect("activate", self.menu_do_wrap, m, it, _DIV.Or) submenu_wrap.append(menu_sub_rule) submenu_wrap.append(menu_and) submenu_wrap.append(menu_or) menu_wrap.set_submenu(submenu_wrap) menu_wrap.show_all() return menu_wrap def menu_do_copy(self, _mitem: Gtk.MenuItem, m: Gtk.TreeStore, it: Gtk.TreeIter): global _rule_component_clipboard wrapped = m[it][0] c = wrapped.component _rule_component_clipboard = _DIV.RuleComponent().compile(c.data()) def menu_do_cut(self, _mitem, m, it): global _rule_component_clipboard c = self.menu_do_delete(_mitem, m, it) self._on_update() _rule_component_clipboard = c def _menu_cut(self, m, it): menu_cut = Gtk.MenuItem(_("Cut")) menu_cut.connect("activate", self.menu_do_cut, m, it) menu_cut.show() return menu_cut def menu_do_paste(self, _mitem, m, it, below=False): global _rule_component_clipboard c = _rule_component_clipboard _rule_component_clipboard = None if c: _rule_component_clipboard = _DIV.RuleComponent().compile(c.data()) self._menu_do_insert(_mitem, m, it, new_c=c, below=below) self._on_update() def _menu_paste(self, m, it, below=False): menu_paste = Gtk.MenuItem(_("Paste")) menu_paste.connect("activate", self.menu_do_paste, m, it, below) menu_paste.show() return menu_paste def _menu_copy(self, m, it): menu_copy = Gtk.MenuItem(_("Copy")) menu_copy.connect("activate", self.menu_do_copy, m, it) menu_copy.show() return menu_copy class DiversionDialog: def __init__(self, action_menu): window = Gtk.Window() window.set_title(_("Solaar Rule Editor")) window.connect("delete-event", self._closing) vbox = Gtk.VBox() self.top_panel, self.view = self._create_top_panel() for col in self._create_view_columns(): self.view.append_column(col) vbox.pack_start(self.top_panel, True, True, 0) self._action_menu = action_menu( window, self.view, populate_model_func=_populate_model, on_update=self.on_update, ) self.dirty = False # if dirty, there are pending changes to be saved self.type_ui = {} self.update_ui = {} self.selected_rule_edit_panel = _create_selected_rule_edit_panel() self.ui = defaultdict(lambda: UnsupportedRuleComponentUI(self.selected_rule_edit_panel)) self.ui.update( { # one instance per type rc_class: rc_ui_class(self.selected_rule_edit_panel, on_update=self.on_update) for rc_class, rc_ui_class in COMPONENT_UI.items() } ) vbox.pack_start(self.selected_rule_edit_panel, False, False, 10) self.model = self._create_model() self.view.set_model(self.model) self.view.expand_all() window.add(vbox) geometry = Gdk.Geometry() geometry.min_width = 600 # don't ask for so much space geometry.min_height = 400 window.set_geometry_hints(None, geometry, Gdk.WindowHints.MIN_SIZE) window.set_position(Gtk.WindowPosition.CENTER) window.show_all() window.connect("delete-event", lambda w, e: w.hide_on_delete() or True) style = window.get_style_context() style.add_class("solaar") self.window = window self._editing_component = None def _closing(self, window: Gtk.Window, e: Gdk.Event): if self.dirty: dialog = _create_close_dialog(window) response = dialog.run() dialog.destroy() if response == Gtk.ResponseType.NO: window.hide() elif response == Gtk.ResponseType.YES: self._save_yaml_file() window.hide() else: # don't close return True else: window.hide() def _reload_yaml_file(self): self.discard_btn.set_sensitive(False) self.save_btn.set_sensitive(False) self.dirty = False for c in self.selected_rule_edit_panel.get_children(): self.selected_rule_edit_panel.remove(c) _DIV.load_config_rule_file() self.model = self._create_model() self.view.set_model(self.model) self.view.expand_all() def _save_yaml_file(self): if _DIV._save_config_rule_file(): self.dirty = False self.save_btn.set_sensitive(False) self.discard_btn.set_sensitive(False) def _create_top_panel(self): sw = Gtk.ScrolledWindow() sw.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.ALWAYS) view = Gtk.TreeView() view.set_headers_visible(False) view.set_enable_tree_lines(True) view.set_reorderable(False) view.connect("key-press-event", self._event_key_pressed) view.connect("button-release-event", self._event_button_released) view.get_selection().connect("changed", self._selection_changed) sw.add(view) sw.set_size_request(0, 300) # don't ask for so much height button_box = Gtk.HBox(spacing=20) self.save_btn = Gtk.Button.new_from_icon_name("document-save", Gtk.IconSize.BUTTON) self.save_btn.set_label(_("Save changes")) self.save_btn.set_always_show_image(True) self.save_btn.set_sensitive(False) self.save_btn.set_valign(Gtk.Align.CENTER) self.discard_btn = Gtk.Button.new_from_icon_name("document-revert", Gtk.IconSize.BUTTON) self.discard_btn.set_label(_("Discard changes")) self.discard_btn.set_always_show_image(True) self.discard_btn.set_sensitive(False) self.discard_btn.set_valign(Gtk.Align.CENTER) self.save_btn.connect("clicked", lambda *_args: self._save_yaml_file()) self.discard_btn.connect("clicked", lambda *_args: self._reload_yaml_file()) button_box.pack_start(self.save_btn, False, False, 0) button_box.pack_start(self.discard_btn, False, False, 0) button_box.set_halign(Gtk.Align.CENTER) button_box.set_valign(Gtk.Align.CENTER) button_box.set_size_request(0, 50) vbox = Gtk.VBox() vbox.pack_start(button_box, False, False, 0) vbox.pack_start(sw, True, True, 0) return vbox, view def _create_model(self): model = Gtk.TreeStore(RuleComponentWrapper) if len(_DIV.rules.components) == 1: # only built-in rules - add empty user rule list _DIV.rules.components.insert(0, _DIV.Rule([], source=_DIV._file_path)) _populate_model(model, None, _DIV.rules.components) return model def _create_view_columns(self): cell_icon = Gtk.CellRendererPixbuf() cell1 = Gtk.CellRendererText() col1 = Gtk.TreeViewColumn("Type") col1.pack_start(cell_icon, False) col1.pack_start(cell1, True) col1.set_cell_data_func(cell1, lambda _c, c, m, it, _d: c.set_property("text", m.get_value(it, 0).display_left())) cell2 = Gtk.CellRendererText() col2 = Gtk.TreeViewColumn("Summary") col2.pack_start(cell2, True) col2.set_cell_data_func(cell2, lambda _c, c, m, it, _d: c.set_property("text", m.get_value(it, 0).display_right())) col2.set_cell_data_func( cell_icon, lambda _c, c, m, it, _d: c.set_property("icon-name", m.get_value(it, 0).display_icon()) ) return col1, col2 def on_update(self): self.view.queue_draw() self.dirty = True self.save_btn.set_sensitive(True) self.discard_btn.set_sensitive(True) def _selection_changed(self, selection): self.selected_rule_edit_panel.set_sensitive(False) (model, it) = selection.get_selected() if it is None: return wrapped = model[it][0] component = wrapped.component self._editing_component = component self.ui[type(component)].show(component, wrapped.editable) self.selected_rule_edit_panel.set_sensitive(wrapped.editable) def _event_key_pressed(self, v, e): """ Shortcuts: Ctrl + I insert component Ctrl + Delete delete row & wrap with And | wrap with Or Shift + R wrap with Rule ! negate Ctrl + X cut Ctrl + C copy Ctrl + V paste below (or here if empty) Ctrl + Shift + V paste above * flatten Ctrl + S save changes """ state = e.state & (Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK) m, it = v.get_selection().get_selected() enabled_actions = allowed_actions(m, it) if state & Gdk.ModifierType.CONTROL_MASK: if enabled_actions.delete and e.keyval in [Gdk.KEY_x, Gdk.KEY_X]: self._action_menu.menu_do_cut(None, m, it) elif enabled_actions.copy and e.keyval in [Gdk.KEY_c, Gdk.KEY_C] and enabled_actions.c is not None: self._action_menu.menu_do_copy(None, m, it) elif enabled_actions.insert and _rule_component_clipboard is not None and e.keyval in [Gdk.KEY_v, Gdk.KEY_V]: self._action_menu.menu_do_paste( None, m, it, below=enabled_actions.c is not None and not (state & Gdk.ModifierType.SHIFT_MASK) ) elif ( enabled_actions.insert_only_rule and isinstance(_rule_component_clipboard, _DIV.Rule) and e.keyval in [Gdk.KEY_v, Gdk.KEY_V] ): self._action_menu.menu_do_paste( None, m, it, below=enabled_actions.c is not None and not (state & Gdk.ModifierType.SHIFT_MASK) ) elif ( enabled_actions.insert_root and isinstance(_rule_component_clipboard, _DIV.Rule) and e.keyval in [Gdk.KEY_v, Gdk.KEY_V] ): self._action_menu.menu_do_paste(None, m, m.iter_nth_child(it, 0)) elif enabled_actions.delete and e.keyval in [Gdk.KEY_KP_Delete, Gdk.KEY_Delete]: self._action_menu.menu_do_delete(None, m, it) elif (enabled_actions.insert or enabled_actions.insert_only_rule or enabled_actions.insert_root) and e.keyval in [ Gdk.KEY_i, Gdk.KEY_I, ]: menu = Gtk.Menu() for item in self._action_menu.get_insert_menus( m, it, enabled_actions, ): menu.append(item) menu.show_all() rect = self.view.get_cell_area(m.get_path(it), self.view.get_column(1)) menu.popup_at_rect(self.window.get_window(), rect, Gdk.Gravity.WEST, Gdk.Gravity.CENTER, e) elif self.dirty and e.keyval in [Gdk.KEY_s, Gdk.KEY_S]: self._save_yaml_file() else: if enabled_actions.wrap: if e.keyval == Gdk.KEY_exclam: self._action_menu.menu_do_negate(None, m, it) elif e.keyval == Gdk.KEY_ampersand: self._action_menu.menu_do_wrap(None, m, it, _DIV.And) elif e.keyval == Gdk.KEY_bar: self._action_menu.menu_do_wrap(None, m, it, _DIV.Or) elif e.keyval in [Gdk.KEY_r, Gdk.KEY_R] and (state & Gdk.ModifierType.SHIFT_MASK): self._action_menu.menu_do_wrap(None, m, it, _DIV.Rule) if enabled_actions.flatten and e.keyval in [Gdk.KEY_asterisk, Gdk.KEY_KP_Multiply]: self._action_menu.menu_do_flatten(None, m, it) def _event_button_released(self, v, e): self._action_menu.create_menu_event_button_released(v, e) def update_devices(self): for rc in self.ui.values(): rc.update_devices() self.view.queue_draw() class CompletionEntry(Gtk.Entry): def __init__(self, values, *args, **kwargs): super().__init__(*args, **kwargs) CompletionEntry.add_completion_to_entry(self, values) @classmethod def add_completion_to_entry(cls, entry, values): completion = entry.get_completion() if not completion: liststore = Gtk.ListStore(str) completion = Gtk.EntryCompletion() completion.set_model(liststore) completion.set_match_func(lambda completion, key, it: norm(key) in norm(completion.get_model()[it][0])) completion.set_text_column(0) entry.set_completion(completion) else: liststore = completion.get_model() liststore.clear() for v in sorted(set(values), key=str.casefold): liststore.append((v,)) class SmartComboBox(Gtk.ComboBox): """A custom ComboBox with some extra features. The constructor requires a collection of allowed values. Each element must be a single value or a non-empty tuple containing: - a value (any hashable object) - a name (optional; str(value) is used if not provided) - alternative names. Example: (some_object, 'object name', 'other name', 'also accept this'). It is assumed that the same string cannot be the name or an alternative name of more than one value. The widget displays the names, but the alternative names are also suggested and accepted as input. If `has_entry` is `True`, then the user can insert arbitrary text (possibly with auto-complete if `completion` is True). Otherwise, only a drop-down list is shown, with an extra blank item in the beginning (correspondent to `None`). The display text of the blank item is defined by the parameter `blank`. If `case_insensitive` is `True`, then upper-case and lower-case letters are treated as equal. If `replace_with_default_name`, then the field text is immediately replaced with the default name of a value as soon as the user finishes typing any accepted name. """ def __init__( self, all_values, blank="", completion=False, case_insensitive=False, replace_with_default_name=False, **kwargs ): super().__init__(**kwargs) self._name_to_idx = {} self._value_to_idx = {} self._hidden_idx = set() self._all_values = [] self._blank = blank self._model = None self._commpletion = completion self._case_insensitive = case_insensitive self._norm = lambda s: None if s is None else s if not case_insensitive else str(s).upper() self._replace_with_default_name = replace_with_default_name def replace_with(value): if self.get_has_entry() and self._replace_with_default_name and value is not None: item = self._all_values[self._value_to_idx[value]] name = item[1] if len(item) > 1 else str(item[0]) if name != self.get_child().get_text(): self.get_child().set_text(name) self.connect("changed", lambda *a: replace_with(self.get_value(invalid_as_str=False))) self.set_id_column(0) if self.get_has_entry(): self.set_entry_text_column(1) else: renderer = Gtk.CellRendererText() self.pack_start(renderer, True) self.add_attribute(renderer, "text", 1) self.set_all_values(all_values) self.set_active_id("") @classmethod def new_model(cls): model = Gtk.ListStore(str, str, bool) # (index: int converted to str, name: str, visible: bool) filtered_model = model.filter_new() filtered_model.set_visible_column(2) return model, filtered_model def set_all_values(self, all_values, visible_fn=(lambda value: True)): old_value = self.get_value() self._name_to_idx = {} self._value_to_idx = {} self._hidden_idx = set() self._all_values = [v if isinstance(v, tuple) else (v,) for v in all_values] model, filtered_model = SmartComboBox.new_model() # creating a new model seems to be necessary to avoid firing 'changed' event once per inserted item model.append(("", self._blank, True)) self._model = model to_complete = [self._blank] for idx, item in enumerate(self._all_values): value, *names = item if isinstance(item, tuple) else (item,) visible = visible_fn(value) self._include(model, idx, value, visible, *names) if visible: to_complete += names if names else [str(value).strip()] self.set_model(filtered_model) if self.get_has_entry() and self._commpletion: CompletionEntry.add_completion_to_entry(self.get_child(), to_complete) if self._find_idx(old_value) is not None: self.set_value(old_value) else: self.set_value(self._blank) self.queue_draw() def _include(self, model, idx, value, visible, *names): name = str(names[0]) if names else str(value).strip() self._name_to_idx[self._norm(name)] = idx if isinstance(value, NamedInt): self._name_to_idx[self._norm(str(name))] = idx model.append((str(idx), name, visible)) for alt in names[1:]: self._name_to_idx[self._norm(str(alt).strip())] = idx self._value_to_idx[value] = idx if self._case_insensitive and isinstance(value, str): self._name_to_idx[self._norm(value)] = idx def get_value(self, invalid_as_str=True, accept_hidden=True): """Return the selected value or the typed text. If the typed or selected text corresponds to one of the allowed values (or their names and alternative names), then the value is returned. Otherwise, the raw text is returned as string if the widget has an entry and `invalid_as_str` is `True`; if the widget has no entry or `invalid_as_str` is `False`, then `None` is returned. """ tree_iter = self.get_active_iter() if tree_iter is not None: t = self.get_model()[tree_iter] number = t[0] return self._all_values[int(number)][0] if number != "" and (accept_hidden or t[2]) else None elif self.get_has_entry(): text = self.get_child().get_text().strip() if text == self._blank: return None idx = self._find_idx(text) if idx is None: return text if invalid_as_str else None item = self._all_values[idx] return item[0] return None def _find_idx(self, search): if search == self._blank: return None try: return self._value_to_idx[search] except KeyError: pass try: return self._name_to_idx[self._norm(search)] except KeyError: pass return None def set_value(self, value, accept_invalid=True): """Set a specific value. Raw values, their names and alternative names are accepted. Base-10 representations of int values as strings are also accepted. The actual value is used in all cases. If `value` is invalid, then the entry text is set to the provided value if the widget has an entry and `accept_invalid` is True, or else the blank value is set. """ idx = self._find_idx(value) if value != self._blank else "" if idx is not None: self.set_active_id(str(idx)) else: if self.get_has_entry() and accept_invalid: self.get_child().set_text(str(value or "") if value != "" else self._blank) else: self.set_active_id("") def show_only(self, only, include_new=False): """Hide items not present in `only`. Only values are accepted (not their names and alternative names). If `include_new` is True, then the values in `only` not currently present are included with their string representation as names; otherwise, they are ignored. If `only` is new, then the visibility status is reset and all values are shown. """ values = self._all_values[:] if include_new and only is not None: values += [v for v in only if v not in self._value_to_idx] self.set_all_values(values, (lambda v: only is None or (v in only))) @dataclass class DeviceInfo: serial: str = "" unitId: str = "" codename: str = "" settings: Dict[str, Setting] = field(default_factory=dict) def __post_init__(self): if self.serial is None or self.serial == "?": self.serial = "" if self.unitId is None or self.unitId == "?": self.unitId = "" @property def id(self) -> str: return self.serial or self.unitId or "" @property def identifiers(self) -> list[str]: return [id for id in (self.serial, self.unitId) if id] @property def display_name(self) -> str: return f"{self.codename} ({self.id})" def matches(self, search: str) -> bool: return search and search in (self.serial, self.unitId, self.display_name) def update(self, device: DeviceInfo) -> None: for k in ("serial", "unitId", "codename", "settings"): if not getattr(self, k, None): v = getattr(device, k, None) if v and v != "?": setattr(self, k, copy(v) if k != "settings" else {s.name: s for s in v}) class DeviceInfoFactory: @classmethod def create_device_info(cls, device) -> DeviceInfo: d = DeviceInfo() d.update(device) return d class AllDevicesInfo: def __init__(self): self._devices: list[DeviceInfo] = [] self._lock = threading.Lock() def __iter__(self): return iter(self._devices) def __getitem__(self, search): if not search: return search assert isinstance(search, str) # linear search - ok because it is always a small list return next((d for d in self._devices if d.matches(search)), None) def refresh(self): updated = False def dev_in_row(_store, _treepath, row): nonlocal updated device = _dev_model.get_value(row, 7) if device and device.kind and (device.serial and device.serial != "?" or device.unitId and device.unitId != "?"): existing = self[device.serial] or self[device.unitId] if not existing: updated = True device_info = DeviceInfoFactory.create_device_info(device) self._devices.append(device_info) elif not existing.settings and device.settings: updated = True existing.update(device) with self._lock: _dev_model.foreach(dev_in_row) return updated class UnsupportedRuleComponentUI(RuleComponentUI): CLASS = None def create_widgets(self): self.label = Gtk.Label(valign=Gtk.Align.CENTER, hexpand=True) self.label.set_text(_("This editor does not support the selected rule component yet.")) self.widgets[self.label] = (0, 0, 1, 1) @classmethod def right_label(cls, component): return str(component) class RuleUI(RuleComponentUI): CLASS = _DIV.Rule def create_widgets(self): self.widgets = {} def collect_value(self): return self.component.components[:] # not editable on the bottom panel @classmethod def left_label(cls, component): return _("Rule") @classmethod def icon_name(cls): return "format-justify-fill" class AndUI(RuleComponentUI): CLASS = _DIV.And def create_widgets(self): self.widgets = {} def collect_value(self): return self.component.components[:] # not editable on the bottom panel @classmethod def left_label(cls, component): return _("And") class OrUI(RuleComponentUI): CLASS = _DIV.Or def create_widgets(self): self.widgets = {} def collect_value(self): return self.component.components[:] # not editable on the bottom panel @classmethod def left_label(cls, component): return _("Or") class LaterUI(RuleComponentUI): CLASS = _DIV.Later MIN_VALUE = 0.01 MAX_VALUE = 100 def create_widgets(self): self.widgets = {} self.label = Gtk.Label(valign=Gtk.Align.CENTER, hexpand=True) self.label.set_text(_("Number of seconds to delay. Delay between 0 and 1 is done with higher precision.")) self.widgets[self.label] = (0, 0, 1, 1) self.field = Gtk.SpinButton.new_with_range(self.MIN_VALUE, self.MAX_VALUE, 1) self.field.set_digits(3) self.field.set_halign(Gtk.Align.CENTER) self.field.set_valign(Gtk.Align.CENTER) self.field.set_hexpand(True) self.field.connect("value-changed", self._on_update) self.widgets[self.field] = (0, 1, 1, 1) def show(self, component, editable): super().show(component, editable) with self.ignore_changes(): self.field.set_value(component.delay) def collect_value(self): return [float(int((self.field.get_value() + 0.0001) * 1000)) / 1000] + self.component.components @classmethod def left_label(cls, component): return _("Later") @classmethod def right_label(cls, component): return str(component.delay) class NotUI(RuleComponentUI): CLASS = _DIV.Not def create_widgets(self): self.widgets = {} def collect_value(self): return self.component.component # not editable on the bottom panel @classmethod def left_label(cls, component): return _("Not") class ActionUI(RuleComponentUI): CLASS = _DIV.Action @classmethod def icon_name(cls): return "go-next" def _from_named_ints(v, all_values): """Obtain a NamedInt from NamedInts given its numeric value (as int) or name.""" if all_values and (v in all_values): return all_values[v] return v class SetValueControlKinds(Enum): TOGGLE = "toggle" RANGE = "range" RANGE_WITH_KEY = "range_with_key" CHOICE = "choice" class SetValueControl(Gtk.HBox): def __init__(self, on_change, *args, accept_toggle=True, **kwargs): super().__init__(*args, **kwargs) self.on_change = on_change self.toggle_widget = SmartComboBox( [ *([("Toggle", _("Toggle"), "~")] if accept_toggle else []), (True, _("True"), "True", "yes", "on", "t", "y"), (False, _("False"), "False", "no", "off", "f", "n"), ], case_insensitive=True, ) self.toggle_widget.connect("changed", self._changed) self.range_widget = Gtk.SpinButton.new_with_range(0, 0xFFFF, 1) self.range_widget.connect("value-changed", self._changed) self.choice_widget = SmartComboBox( [], completion=True, has_entry=True, case_insensitive=True, replace_with_default_name=True ) self.choice_widget.connect("changed", self._changed) self.sub_key_widget = SmartComboBox([]) self.sub_key_widget.connect("changed", self._changed) self.unsupported_label = Gtk.Label(label=_("Unsupported setting")) self.pack_start(self.sub_key_widget, False, False, 0) self.sub_key_widget.set_hexpand(False) self.sub_key_widget.set_size_request(120, 0) self.sub_key_widget.hide() for w in [self.toggle_widget, self.range_widget, self.choice_widget, self.unsupported_label]: self.pack_end(w, True, True, 0) w.hide() self.unsupp_value = None self.current_kind: Optional[SetValueControlKinds] = None self.sub_key_range_items = None def _changed(self, widget, *args): if widget.get_visible(): value = self.get_value() if self.current_kind == SetValueControlKinds.CHOICE: value = widget.get_value() icon = "dialog-warning" if widget._allowed_values and (value not in widget._allowed_values) else "" widget.get_child().set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, icon) elif self.current_kind == SetValueControlKinds.RANGE_WITH_KEY and widget == self.sub_key_widget: key = self.sub_key_widget.get_value() selected_item = ( next((item for item in self.sub_key_range_items if key == item.id), None) if self.sub_key_range_items else None ) (minimum, maximum) = (selected_item.minimum, selected_item.maximum) if selected_item else (0, 0xFFFF) self.range_widget.set_range(minimum, maximum) self.on_change(value) def _hide_all(self): for w in self.get_children(): w.hide() def get_value(self): if self.current_kind == SetValueControlKinds.TOGGLE: return self.toggle_widget.get_value() if self.current_kind == SetValueControlKinds.RANGE: return int(self.range_widget.get_value()) if self.current_kind == SetValueControlKinds.RANGE_WITH_KEY: return {self.sub_key_widget.get_value(): int(self.range_widget.get_value())} if self.current_kind == SetValueControlKinds.CHOICE: return self.choice_widget.get_value() return self.unsupp_value def set_value(self, value): if self.current_kind == SetValueControlKinds.TOGGLE: self.toggle_widget.set_value(value if value is not None else "") elif self.current_kind == SetValueControlKinds.RANGE: minimum, maximum = self.range_widget.get_range() try: v = round(float(value)) except (ValueError, TypeError): v = minimum self.range_widget.set_value(max(minimum, min(maximum, v))) elif self.current_kind == SetValueControlKinds.RANGE_WITH_KEY: if not (isinstance(value, dict) and len(value) == 1): value = {None: None} key = next(iter(value.keys())) selected_item = ( next((item for item in self.sub_key_range_items if key == item.id), None) if self.sub_key_range_items else None ) (minimum, maximum) = (selected_item.minimum, selected_item.maximum) if selected_item else (0, 0xFFFF) try: v = round(float(next(iter(value.values())))) except (ValueError, TypeError): v = minimum self.sub_key_widget.set_value(key or "") self.range_widget.set_value(max(minimum, min(maximum, v))) elif self.current_kind == SetValueControlKinds.CHOICE: self.choice_widget.set_value(value) else: self.unsupp_value = value if value is None or value == "": # reset all self.range_widget.set_range(0x0000, 0xFFFF) self.range_widget.set_value(0) self.toggle_widget.set_active_id("") self.sub_key_widget.set_value("") self.choice_widget.set_value("") def make_toggle(self): self.current_kind = SetValueControlKinds.TOGGLE self._hide_all() self.toggle_widget.show() def make_range(self, minimum, maximum): self.current_kind = SetValueControlKinds.RANGE self._hide_all() self.range_widget.set_range(minimum, maximum) self.range_widget.show() def make_range_with_key(self, items, labels=None): self.current_kind = SetValueControlKinds.RANGE_WITH_KEY self._hide_all() self.sub_key_range_items = items or None if not labels: labels = {} self.sub_key_widget.set_all_values( map(lambda item: (item.id, labels.get(item.id, [str(item.id)])[0]), items) if items else [] ) self.sub_key_widget.show() self.range_widget.show() def make_choice(self, values, extra=None): # if extra is not in values, it is ignored self.current_kind = SetValueControlKinds.CHOICE self._hide_all() sort_key = int if all((v == extra or str(v).isdigit()) for v in values) else str if extra is not None and extra in values: values = [extra] + sorted((v for v in values if v != extra), key=sort_key) else: values = sorted(values, key=sort_key) self.choice_widget.set_all_values(values) self.choice_widget._allowed_values = values self.choice_widget.show() def make_unsupported(self): self.current_kind = None self._hide_all() self.unsupported_label.show() def _all_settings(): settings = {} for s in sorted(SETTINGS, key=lambda setting: setting.label): if s.name not in settings: settings[s.name] = [s] else: prev_setting = settings[s.name][0] prev_kind = prev_setting.validator_class.kind if prev_kind != s.validator_class.kind: logger.warning( "ignoring setting {} - same name of {}, but different kind ({} != {})".format( s.__name__, prev_setting.__name__, prev_kind, s.validator_class.kind ) ) continue settings[s.name].append(s) return settings class _DeviceUI: label_text = "" def show(self, component, editable): super().show(component, editable) with self.ignore_changes(): same = not component.devID device = _all_devices[component.devID] self.device_field.set_value(device.id if device else "" if same else component.devID or "") def create_widgets(self): self.widgets = {} self.label = Gtk.Label(valign=Gtk.Align.CENTER, hexpand=True) self.label.set_text(self.label_text) self.widgets[self.label] = (0, 0, 5, 1) lbl = Gtk.Label(label=_("Device"), halign=Gtk.Align.CENTER, valign=Gtk.Align.CENTER, hexpand=True) self.widgets[lbl] = (0, 1, 1, 1) self.device_field = SmartComboBox( [], completion=True, has_entry=True, blank=_("Originating device"), case_insensitive=True, replace_with_default_name=True, ) self.device_field.set_value("") self.device_field.set_valign(Gtk.Align.CENTER) self.device_field.set_size_request(400, 0) self.device_field.connect("changed", self._on_update) self.widgets[self.device_field] = (1, 1, 1, 1) def update_devices(self): self._update_device_list() def _update_device_list(self): with self.ignore_changes(): self.device_field.set_all_values([(d.id, d.display_name, *d.identifiers[1:]) for d in _all_devices]) def collect_value(self): device_str = self.device_field.get_value() same = device_str in ["", _("Originating device")] device = None if same else _all_devices[device_str] device_value = device.id if device else None if same else device_str return device_value @classmethod def right_label(cls, component): device = _all_devices[component.devID] return device.display_name if device else shlex_quote(component.devID) class ActiveUI(_DeviceUI, ConditionUI): CLASS = _DIV.Active label_text = _("Device is active and its settings can be changed.") @classmethod def left_label(cls, component): return _("Active") class DeviceUI(_DeviceUI, ConditionUI): CLASS = _DIV.Device label_text = _("Device that originated the current notification.") @classmethod def left_label(cls, component): return _("Device") class HostUI(ConditionUI): CLASS = _DIV.Host def create_widgets(self): self.widgets = {} self.label = Gtk.Label(valign=Gtk.Align.CENTER, hexpand=True) self.label.set_text(_("Name of host computer.")) self.widgets[self.label] = (0, 0, 1, 1) self.field = Gtk.Entry(halign=Gtk.Align.CENTER, valign=Gtk.Align.CENTER, hexpand=True) self.field.set_size_request(600, 0) self.field.connect("changed", self._on_update) self.widgets[self.field] = (0, 1, 1, 1) def show(self, component, editable): super().show(component, editable) with self.ignore_changes(): self.field.set_text(component.host) def collect_value(self): return self.field.get_text() @classmethod def left_label(cls, component): return _("Host") @classmethod def right_label(cls, component): return str(component.host) class _SettingWithValueUI: ALL_SETTINGS = _all_settings() MULTIPLE = [_SKIND.multiple_toggle, _SKIND.map_choice, _SKIND.multiple_range] ACCEPT_TOGGLE = True label_text = "" def create_widgets(self): self.widgets = {} self.label = Gtk.Label(valign=Gtk.Align.CENTER, hexpand=True) self.label.set_text(self.label_text) self.widgets[self.label] = (0, 0, 5, 1) m = 20 lbl = Gtk.Label(label=_("Device"), halign=Gtk.Align.CENTER, valign=Gtk.Align.CENTER, hexpand=True, margin_top=m) self.widgets[lbl] = (0, 1, 1, 1) self.device_field = SmartComboBox( [], completion=True, has_entry=True, blank=_("Originating device"), case_insensitive=True, replace_with_default_name=True, ) self.device_field.set_value("") self.device_field.set_valign(Gtk.Align.CENTER) self.device_field.set_size_request(400, 0) self.device_field.set_margin_top(m) self.device_field.connect("changed", self._changed_device) self.device_field.connect("changed", self._on_update) self.widgets[self.device_field] = (1, 1, 1, 1) lbl = Gtk.Label( label=_("Setting"), halign=Gtk.Align.CENTER, valign=Gtk.Align.CENTER, hexpand=True, vexpand=False, ) self.widgets[lbl] = (0, 2, 1, 1) self.setting_field = SmartComboBox([(s[0].name, s[0].label) for s in self.ALL_SETTINGS.values()]) self.setting_field.set_valign(Gtk.Align.CENTER) self.setting_field.connect("changed", self._changed_setting) self.setting_field.connect("changed", self._on_update) self.widgets[self.setting_field] = (1, 2, 1, 1) self.value_lbl = Gtk.Label( label=_("Value"), halign=Gtk.Align.CENTER, valign=Gtk.Align.CENTER, hexpand=True, vexpand=False ) self.widgets[self.value_lbl] = (2, 2, 1, 1) self.value_field = SetValueControl(self._on_update, accept_toggle=self.ACCEPT_TOGGLE) self.value_field.set_valign(Gtk.Align.CENTER) self.value_field.set_size_request(250, 35) self.widgets[self.value_field] = (3, 2, 1, 1) self.key_lbl = Gtk.Label( label=_("Item"), halign=Gtk.Align.CENTER, valign=Gtk.Align.CENTER, hexpand=True, vexpand=False, margin_top=m ) self.key_lbl.hide() self.widgets[self.key_lbl] = (2, 1, 1, 1) self.key_field = SmartComboBox( [], has_entry=True, completion=True, case_insensitive=True, replace_with_default_name=True ) self.key_field.set_margin_top(m) self.key_field.hide() self.key_field.set_valign(Gtk.Align.CENTER) self.key_field.connect("changed", self._changed_key) self.key_field.connect("changed", self._on_update) self.widgets[self.key_field] = (3, 1, 1, 1) @classmethod def _all_choices(cls, setting): # choice and map-choice """Return a NamedInts instance with the choices for a setting. If the argument `setting` is a Setting instance or subclass, then the choices are taken only from it. If instead it is a name, then the function returns the union of the choices for each setting with that name. Only one label per number is kept. The function returns a 2-tuple whose first element is a NamedInts instance with the possible choices (including the extra value if it exists) and the second element is the extra value to be pinned to the start of the list (or `None` if there is no extra value). """ if isinstance(setting, Setting): setting = type(setting) if isinstance(setting, type) and issubclass(setting, Setting): choices = UnsortedNamedInts() universe = getattr(setting, "choices_universe", None) if universe: choices |= universe extra = getattr(setting, "choices_extra", None) if extra is not None: choices |= NamedInts(**{str(extra): int(extra)}) return choices, extra settings = cls.ALL_SETTINGS.get(setting, []) choices = UnsortedNamedInts() extra = None for s in settings: ch, ext = cls._all_choices(s) choices |= ch if ext is not None: extra = ext return choices, extra @classmethod def _setting_attributes(cls, setting_name, device=None): if device and setting_name in device.settings: setting = device.settings.get(setting_name, None) settings = [type(setting)] if setting else None else: settings = cls.ALL_SETTINGS.get(setting_name, [None]) setting = settings[0] # if settings have the same name, use the first one to get the basic data val_class = setting.validator_class if setting else None kind = val_class.kind if val_class else None if kind in cls.MULTIPLE: keys = UnsortedNamedInts() for s in settings: universe = getattr(s, "keys_universe" if kind == _SKIND.map_choice else "choices_universe", None) if universe: keys |= universe # only one key per number is used else: keys = None return setting, val_class, kind, keys def _changed_device(self, *args): device = _all_devices[self.device_field.get_value()] setting_name = self.setting_field.get_value() if not device or not device.settings or setting_name in device.settings: kind = self._setting_attributes(setting_name, device)[2] key = self.key_field.get_value() if kind in self.MULTIPLE else None else: setting_name = kind = key = None with self.ignore_changes(): self._update_setting_list(device) self._update_key_list(setting_name, device) self._update_value_list(setting_name, device, key) def _changed_setting(self, *args): with self.ignore_changes(): device = _all_devices[self.device_field.get_value()] setting_name = self.setting_field.get_value() self._update_key_list(setting_name, device) key = self.key_field.get_value() self._update_value_list(setting_name, device, key) def _changed_key(self, *args): with self.ignore_changes(): setting_name = self.setting_field.get_value() device = _all_devices[self.device_field.get_value()] key = self.key_field.get_value() self._update_value_list(setting_name, device, key) def update_devices(self): self._update_device_list() def _update_device_list(self): with self.ignore_changes(): self.device_field.set_all_values([(d.id, d.display_name, *d.identifiers[1:]) for d in _all_devices]) def _update_setting_list(self, device=None): supported_settings = device.settings.keys() if device else {} with self.ignore_changes(): self.setting_field.show_only(supported_settings or None) def _update_key_list(self, setting_name, device=None): setting, val_class, kind, keys = self._setting_attributes(setting_name, device) multiple = kind in self.MULTIPLE self.key_field.set_visible(multiple) self.key_lbl.set_visible(multiple) if not multiple: return labels = getattr(setting, "_labels", {}) def item(k): lbl = labels.get(k, None) if lbl and isinstance(lbl, tuple) and lbl[0]: label = lbl[0] else: label = str(k) return k, label with self.ignore_changes(): self.key_field.set_all_values(sorted(map(item, keys), key=lambda k: k[1])) ds = device.settings if device else {} device_setting = ds.get(setting_name, None) supported_keys = None if device_setting: val = device_setting._validator if device_setting.kind == _SKIND.multiple_toggle: supported_keys = val.get_options() or None elif device_setting.kind == _SKIND.map_choice: choices = val.choices or None supported_keys = choices.keys() if choices else None elif device_setting.kind == _SKIND.multiple_range: supported_keys = val.keys self.key_field.show_only(supported_keys, include_new=True) self._update_validation() def _update_value_list(self, setting_name, device=None, key=None): setting, val_class, kind, keys = self._setting_attributes(setting_name, device) ds = device.settings if device else {} device_setting = ds.get(setting_name, None) if kind in (_SKIND.toggle, _SKIND.multiple_toggle): self.value_field.make_toggle() elif kind in (_SKIND.choice, _SKIND.map_choice): all_values, extra = self._all_choices(device_setting or setting_name) self.value_field.make_choice(all_values, extra) supported_values = None if device_setting: val = device_setting._validator choices = getattr(val, "choices", None) or None if kind == _SKIND.choice: supported_values = choices elif kind == _SKIND.map_choice and isinstance(choices, dict): supported_values = choices.get(key, None) or None self.value_field.choice_widget.show_only(supported_values, include_new=True) self._update_validation() elif kind == _SKIND.range: self.value_field.make_range(val_class.min_value, val_class.max_value) elif kind == _SKIND.multiple_range: self.value_field.make_range_with_key( getattr(setting, "sub_items_universe", {}).get(key, {}) if setting else {}, getattr(setting, "_labels_sub", None) if setting else None, ) else: self.value_field.make_unsupported() def _on_update(self, *_args): if not self._ignore_changes and self.component: self._update_validation() def _update_validation(self): device_str = self.device_field.get_value() device = _all_devices[device_str] if device_str and not device: icon = ( "dialog-question" if len(device_str) == 8 and all(c in string.hexdigits for c in device_str) else "dialog-warning" ) else: icon = "" self.device_field.get_child().set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, icon) setting_name = self.setting_field.get_value() setting, val_class, kind, keys = self._setting_attributes(setting_name, device) multiple = kind in self.MULTIPLE if multiple: key = self.key_field.get_value(invalid_as_str=False, accept_hidden=False) icon = "dialog-warning" if key is None else "" self.key_field.get_child().set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, icon) if kind in (_SKIND.choice, _SKIND.map_choice): value = self.value_field.choice_widget.get_value(invalid_as_str=False, accept_hidden=False) icon = "dialog-warning" if value is None else "" self.value_field.choice_widget.get_child().set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, icon) def show(self, component, editable): a = iter(component.args) with self.ignore_changes(): device_str = next(a, None) same = not device_str device = _all_devices[device_str] self.device_field.set_value(device.id if device else "" if same else device_str or "") setting_name = next(a, "") setting, _v, kind, keys = self._setting_attributes(setting_name, device) self.setting_field.set_value(setting.name if setting else "") self._changed_setting() key = None if kind in self.MULTIPLE or kind is None and len(self.component.args) > 3: key = _from_named_ints(next(a, ""), keys) self.key_field.set_value(key) self.value_field.set_value(next(a, "")) self._update_validation() def collect_value(self): device_str = self.device_field.get_value() same = device_str in ["", _("Originating device")] device = None if same else _all_devices[device_str] device_value = device.id if device else None if same else device_str setting_name = self.setting_field.get_value() setting, val_class, kind, keys = self._setting_attributes(setting_name, device) key_value = [] if kind in self.MULTIPLE or kind is None and len(self.component.args) > 3: key = self.key_field.get_value() key = _from_named_ints(key, keys) key_value.append(key) key_value.append(self.value_field.get_value()) return [device_value, setting_name, *key_value] @classmethod def right_label(cls, component): a = iter(component.args) device_str = next(a, None) device = None if not device_str else _all_devices[device_str] device_disp = _("Originating device") if not device_str else device.display_name if device else shlex_quote(device_str) setting_name = next(a, None) setting, val_class, kind, keys = cls._setting_attributes(setting_name, device) device_setting = (device.settings if device else {}).get(setting_name, None) disp = [setting.label or setting.name if setting else setting_name] key = None if kind in cls.MULTIPLE: key = next(a, None) key = _from_named_ints(key, keys) if keys else key key_label = getattr(setting, "_labels", {}).get(key, [None])[0] if setting else None disp.append(key_label or key) value = next(a, None) if setting and (kind in (_SKIND.choice, _SKIND.map_choice)): all_values = cls._all_choices(setting or setting_name)[0] supported_values = None if device_setting: val = device_setting._validator choices = getattr(val, "choices", None) or None if kind == _SKIND.choice: supported_values = choices elif kind == _SKIND.map_choice and isinstance(choices, dict): supported_values = choices.get(key, None) or None if supported_values and isinstance(supported_values, NamedInts): value = supported_values[value] if not supported_values and all_values and isinstance(all_values, NamedInts): value = all_values[value] disp.append(value) elif kind == _SKIND.multiple_range and isinstance(value, dict) and len(value) == 1: k, v = next(iter(value.items())) k = (getattr(setting, "_labels_sub", {}).get(k, (None,))[0] if setting else None) or k disp.append(f"{k}={v}") elif kind in (_SKIND.toggle, _SKIND.multiple_toggle): disp.append(_(str(value))) else: disp.append(value) return device_disp + " " + " ".join(map(lambda s: shlex_quote(str(s)), [*disp, *a])) class SetUI(_SettingWithValueUI, ActionUI): CLASS = _DIV.Set ACCEPT_TOGGLE = True label_text = _("Change setting on device") def show(self, component, editable): ActionUI.show(self, component, editable) _SettingWithValueUI.show(self, component, editable) def _on_update(self, *_args): if not self._ignore_changes and self.component: ActionUI._on_update(self, *_args) _SettingWithValueUI._on_update(self, *_args) class SettingUI(_SettingWithValueUI, ConditionUI): CLASS = _DIV.Setting ACCEPT_TOGGLE = False label_text = _("Setting on device") def show(self, component, editable): ConditionUI.show(self, component, editable) _SettingWithValueUI.show(self, component, editable) def _on_update(self, *_args): if not self._ignore_changes and self.component: ConditionUI._on_update(self, *_args) _SettingWithValueUI._on_update(self, *_args) COMPONENT_UI = { _DIV.Rule: RuleUI, _DIV.Not: NotUI, _DIV.Or: OrUI, _DIV.And: AndUI, _DIV.Later: LaterUI, _DIV.Process: rule_conditions.ProcessUI, _DIV.MouseProcess: rule_conditions.MouseProcessUI, _DIV.Active: ActiveUI, _DIV.Device: DeviceUI, _DIV.Host: HostUI, _DIV.Feature: rule_conditions.FeatureUI, _DIV.Report: rule_conditions.ReportUI, _DIV.Modifiers: rule_conditions.ModifiersUI, _DIV.Key: rule_conditions.KeyUI, _DIV.KeyIsDown: rule_conditions.KeyIsDownUI, _DIV.Test: rule_conditions.TestUI, _DIV.TestBytes: rule_conditions.TestBytesUI, _DIV.Setting: SettingUI, _DIV.MouseGesture: rule_conditions.MouseGestureUI, _DIV.KeyPress: rule_actions.KeyPressUI, _DIV.MouseScroll: rule_actions.MouseScrollUI, _DIV.MouseClick: rule_actions.MouseClickUI, _DIV.Execute: rule_actions.ExecuteUI, _DIV.Set: SetUI, type(None): RuleComponentUI, # placeholders for empty rule/And/Or } _all_devices = AllDevicesInfo() _dev_model = None def update_devices(): global _dev_model global _all_devices global _diversion_dialog if _dev_model and _all_devices.refresh() and _diversion_dialog: _diversion_dialog.update_devices() def show_window(model: Gtk.TreeStore): GObject.type_register(RuleComponentWrapper) global _diversion_dialog global _dev_model _dev_model = model if _diversion_dialog is None: _diversion_dialog = DiversionDialog(ActionMenu) update_devices() _diversion_dialog.window.present()
74,730
Python
.py
1,621
35.969772
127
0.602144
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,489
action.py
pwr-Solaar_Solaar/lib/solaar/ui/action.py
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/ ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from gi.repository import Gdk from gi.repository import Gtk from solaar.i18n import _ from . import pair_window from .common import error_dialog def make_image_menu_item(label, icon_name, function, *args): box = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 6) label = Gtk.Label(label=label) icon = Gtk.Image.new_from_icon_name(icon_name, Gtk.IconSize.LARGE_TOOLBAR) if icon_name is not None else Gtk.Image() box.add(icon) box.add(label) menu_item = Gtk.MenuItem() menu_item.add(box) menu_item.show_all() menu_item.connect("activate", function, *args) menu_item.label = label menu_item.icon = icon return menu_item def make(name, label, function, stock_id=None, *args): action = Gtk.Action(name=name, label=label, tooltip=label, stock_id=None) action.set_icon_name(name) if stock_id is not None: action.set_stock_id(stock_id) if function: action.connect("activate", function, *args) return action def make_toggle(name, label, function, stock_id=None, *args): action = Gtk.ToggleAction(name=name, label=label, tooltip=label, stock_id=None) action.set_icon_name(name) if stock_id is not None: action.set_stock_id(stock_id) action.connect("activate", function, *args) return action def pair(window, receiver): assert receiver assert receiver.kind is None pair_dialog = pair_window.create(receiver) pair_dialog.set_transient_for(window) pair_dialog.set_destroy_with_parent(True) pair_dialog.set_modal(True) pair_dialog.set_type_hint(Gdk.WindowTypeHint.DIALOG) pair_dialog.set_position(Gtk.WindowPosition.CENTER) pair_dialog.present() def unpair(window, device): assert device assert device.kind is not None qdialog = Gtk.MessageDialog( transient_for=window, flags=0, message_type=Gtk.MessageType.QUESTION, buttons=Gtk.ButtonsType.NONE, text=_("Unpair") + " " + device.name + " ?", ) qdialog.set_icon_name("remove") qdialog.add_button(_("Cancel"), Gtk.ResponseType.CANCEL) qdialog.add_button(_("Unpair"), Gtk.ResponseType.ACCEPT) choice = qdialog.run() qdialog.destroy() if choice == Gtk.ResponseType.ACCEPT: receiver = device.receiver assert receiver device_number = device.number try: del receiver[device_number] except Exception: error_dialog("unpair", device)
3,307
Python
.py
82
35.573171
120
0.712371
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,490
common.py
pwr-Solaar_Solaar/lib/solaar/ui/common.py
## Copyright (C) 2012-2013 Daniel Pavel ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import logging from typing import Tuple import gi from solaar.i18n import _ from solaar.tasks import TaskRunner gi.require_version("Gtk", "3.0") from gi.repository import GLib # NOQA: E402 from gi.repository import Gtk # NOQA: E402 logger = logging.getLogger(__name__) def _create_error_text(reason: str, object_) -> Tuple[str, str]: if reason == "permissions": title = _("Permissions error") text = ( _("Found a Logitech receiver or device (%s), but did not have permission to open it.") % object_ + "\n\n" + _("If you've just installed Solaar, try disconnecting the receiver or device and then reconnecting it.") ) elif reason == "nodevice": title = _("Cannot connect to device error") text = ( _("Found a Logitech receiver or device at %s, but encountered an error connecting to it.") % object_ + "\n\n" + _("Try disconnecting the device and then reconnecting it or turning it off and then on.") ) elif reason == "unpair": title = _("Unpairing failed") text = ( _("Failed to unpair %{device} from %{receiver}.").format( device=object_.name, receiver=object_.receiver.name, ) + "\n\n" + _("The receiver returned an error, with no further details.") ) else: raise Exception("ui.error_dialog: don't know how to handle (%s, %s)", reason, object_) return title, text def _error_dialog(reason: str, object_): logger.error("error: %s %s", reason, object_) title, text = _create_error_text(reason, object_) m = Gtk.MessageDialog(None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE, text) m.set_title(title) m.run() m.destroy() def error_dialog(reason, object_): assert reason is not None GLib.idle_add(_error_dialog, reason, object_) _task_runner = None def start_async(): global _task_runner _task_runner = TaskRunner("AsyncUI") _task_runner.start() def stop_async(): global _task_runner _task_runner.stop() _task_runner = None def ui_async(function, *args, **kwargs): if _task_runner: _task_runner(function, *args, **kwargs)
3,048
Python
.py
74
35.581081
118
0.662716
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,491
rule_actions.py
pwr-Solaar_Solaar/lib/solaar/ui/rule_actions.py
## Copyright (C) Solaar Contributors ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from shlex import quote as shlex_quote from gi.repository import Gtk from logitech_receiver import diversion from logitech_receiver.diversion import CLICK from logitech_receiver.diversion import DEPRESS from logitech_receiver.diversion import RELEASE from logitech_receiver.diversion import XK_KEYS from logitech_receiver.diversion import buttons from solaar.i18n import _ from solaar.ui.rule_base import CompletionEntry from solaar.ui.rule_base import RuleComponentUI class ActionUI(RuleComponentUI): CLASS = diversion.Action @classmethod def icon_name(cls): return "go-next" class KeyPressUI(ActionUI): CLASS = diversion.KeyPress KEY_NAMES = [k[3:] if k.startswith("XK_") else k for k, v in XK_KEYS.items() if isinstance(v, int)] def create_widgets(self): self.widgets = {} self.fields = [] self.label = Gtk.Label( label=_("Simulate a chorded key click or depress or release.\nOn Wayland requires write access to /dev/uinput."), halign=Gtk.Align.CENTER, ) self.widgets[self.label] = (0, 0, 5, 1) self.del_btns = [] self.add_btn = Gtk.Button(label=_("Add key"), halign=Gtk.Align.CENTER, valign=Gtk.Align.END, hexpand=True) self.add_btn.connect("clicked", self._clicked_add) self.widgets[self.add_btn] = (1, 1, 1, 1) self.action_clicked_radio = Gtk.RadioButton.new_with_label_from_widget(None, _("Click")) self.action_clicked_radio.connect("toggled", self._on_update, CLICK) self.widgets[self.action_clicked_radio] = (0, 3, 1, 1) self.action_pressed_radio = Gtk.RadioButton.new_with_label_from_widget(self.action_clicked_radio, _("Depress")) self.action_pressed_radio.connect("toggled", self._on_update, DEPRESS) self.widgets[self.action_pressed_radio] = (1, 3, 1, 1) self.action_released_radio = Gtk.RadioButton.new_with_label_from_widget(self.action_pressed_radio, _("Release")) self.action_released_radio.connect("toggled", self._on_update, RELEASE) self.widgets[self.action_released_radio] = (2, 3, 1, 1) def _create_field(self): field_entry = CompletionEntry(self.KEY_NAMES, halign=Gtk.Align.CENTER, valign=Gtk.Align.END, hexpand=True) field_entry.connect("changed", self._on_update) self.fields.append(field_entry) self.widgets[field_entry] = (len(self.fields) - 1, 1, 1, 1) return field_entry def _create_del_btn(self): btn = Gtk.Button(label=_("Delete"), halign=Gtk.Align.CENTER, valign=Gtk.Align.START, hexpand=True) self.del_btns.append(btn) self.widgets[btn] = (len(self.del_btns) - 1, 2, 1, 1) btn.connect("clicked", self._clicked_del, len(self.del_btns) - 1) return btn def _clicked_add(self, _btn): keys, action = self.component.regularize_args(self.collect_value()) self.component.__init__([keys + [""], action], warn=False) self.show(self.component, editable=True) self.fields[len(self.component.key_names) - 1].grab_focus() def _clicked_del(self, _btn, pos): keys, action = self.component.regularize_args(self.collect_value()) keys.pop(pos) self.component.__init__([keys, action], warn=False) self.show(self.component, editable=True) self._on_update_callback() def _on_update(self, *args): super()._on_update(*args) for i, f in enumerate(self.fields): if f.get_visible(): icon = ( "dialog-warning" if i < len(self.component.key_names) and self.component.key_names[i] not in self.KEY_NAMES else "" ) f.set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, icon) def show(self, component, editable=True): n = len(component.key_names) while len(self.fields) < n: self._create_field() self._create_del_btn() self.widgets[self.add_btn] = (n, 1, 1, 1) super().show(component, editable) for i in range(n): field_entry = self.fields[i] with self.ignore_changes(): field_entry.set_text(component.key_names[i]) field_entry.set_size_request(int(0.3 * self.panel.get_toplevel().get_size()[0]), 0) field_entry.show_all() self.del_btns[i].show() for i in range(n, len(self.fields)): self.fields[i].hide() self.del_btns[i].hide() def collect_value(self): action = ( CLICK if self.action_clicked_radio.get_active() else DEPRESS if self.action_pressed_radio.get_active() else RELEASE ) return [[f.get_text().strip() for f in self.fields if f.get_visible()], action] @classmethod def left_label(cls, component): return _("Key press") @classmethod def right_label(cls, component): return " + ".join(component.key_names) + (" (" + component.action + ")" if component.action != CLICK else "") class MouseScrollUI(ActionUI): CLASS = diversion.MouseScroll MIN_VALUE = -2000 MAX_VALUE = 2000 def create_widgets(self): self.widgets = {} self.label = Gtk.Label( label=_("Simulate a mouse scroll.\nOn Wayland requires write access to /dev/uinput."), halign=Gtk.Align.CENTER ) self.widgets[self.label] = (0, 0, 4, 1) self.label_x = Gtk.Label(label="x", halign=Gtk.Align.END, valign=Gtk.Align.END, hexpand=True) self.label_y = Gtk.Label(label="y", halign=Gtk.Align.END, valign=Gtk.Align.END, hexpand=True) self.field_x = Gtk.SpinButton.new_with_range(self.MIN_VALUE, self.MAX_VALUE, 1) self.field_y = Gtk.SpinButton.new_with_range(self.MIN_VALUE, self.MAX_VALUE, 1) for f in [self.field_x, self.field_y]: f.set_halign(Gtk.Align.CENTER) f.set_valign(Gtk.Align.START) self.field_x.connect("changed", self._on_update) self.field_y.connect("changed", self._on_update) self.widgets[self.label_x] = (0, 1, 1, 1) self.widgets[self.field_x] = (1, 1, 1, 1) self.widgets[self.label_y] = (2, 1, 1, 1) self.widgets[self.field_y] = (3, 1, 1, 1) @classmethod def __parse(cls, v): try: # allow floats, but round them down return int(float(v)) except (TypeError, ValueError): return 0 def show(self, component, editable=True): super().show(component, editable) with self.ignore_changes(): self.field_x.set_value(self.__parse(component.amounts[0] if len(component.amounts) >= 1 else 0)) self.field_y.set_value(self.__parse(component.amounts[1] if len(component.amounts) >= 2 else 0)) def collect_value(self): return [int(self.field_x.get_value()), int(self.field_y.get_value())] @classmethod def left_label(cls, component): return _("Mouse scroll") @classmethod def right_label(cls, component): x = y = 0 x = cls.__parse(component.amounts[0] if len(component.amounts) >= 1 else 0) y = cls.__parse(component.amounts[1] if len(component.amounts) >= 2 else 0) return f"{x}, {y}" class MouseClickUI(ActionUI): CLASS = diversion.MouseClick MIN_VALUE = 1 MAX_VALUE = 9 BUTTONS = list(buttons.keys()) ACTIONS = [CLICK, DEPRESS, RELEASE] def create_widgets(self): self.widgets = {} self.label = Gtk.Label( label=_("Simulate a mouse click.\nOn Wayland requires write access to /dev/uinput."), halign=Gtk.Align.CENTER ) self.widgets[self.label] = (0, 0, 4, 1) self.label_b = Gtk.Label(label=_("Button"), halign=Gtk.Align.END, valign=Gtk.Align.CENTER, hexpand=True) self.label_c = Gtk.Label(label=_("Count and Action"), halign=Gtk.Align.END, valign=Gtk.Align.CENTER, hexpand=True) self.field_b = CompletionEntry(self.BUTTONS) self.field_c = Gtk.SpinButton.new_with_range(self.MIN_VALUE, self.MAX_VALUE, 1) self.field_d = CompletionEntry(self.ACTIONS) for f in [self.field_b, self.field_c]: f.set_halign(Gtk.Align.CENTER) f.set_valign(Gtk.Align.START) self.field_b.connect("changed", self._on_update) self.field_c.connect("changed", self._on_update) self.field_d.connect("changed", self._on_update) self.widgets[self.label_b] = (0, 1, 1, 1) self.widgets[self.field_b] = (1, 1, 1, 1) self.widgets[self.label_c] = (2, 1, 1, 1) self.widgets[self.field_c] = (3, 1, 1, 1) self.widgets[self.field_d] = (4, 1, 1, 1) def show(self, component, editable=True): super().show(component, editable) with self.ignore_changes(): self.field_b.set_text(component.button) if isinstance(component.count, int): self.field_c.set_value(component.count) self.field_d.set_text(CLICK) else: self.field_c.set_value(1) self.field_d.set_text(component.count) def collect_value(self): b, c, d = self.field_b.get_text(), int(self.field_c.get_value()), self.field_d.get_text() if b not in self.BUTTONS: b = "unknown" if d != CLICK: c = d return [b, c] @classmethod def left_label(cls, component): return _("Mouse click") @classmethod def right_label(cls, component): return f'{component.button} ({"x" if isinstance(component.count, int) else ""}{component.count})' class ExecuteUI(ActionUI): CLASS = diversion.Execute def create_widgets(self): self.widgets = {} self.label = Gtk.Label(label=_("Execute a command with arguments."), halign=Gtk.Align.CENTER) self.widgets[self.label] = (0, 0, 5, 1) self.fields = [] self.add_btn = Gtk.Button(label=_("Add argument"), halign=Gtk.Align.CENTER, valign=Gtk.Align.END, hexpand=True) self.del_btns = [] self.add_btn.connect("clicked", self._clicked_add) self.widgets[self.add_btn] = (1, 1, 1, 1) def _create_field(self): field_entry = Gtk.Entry(halign=Gtk.Align.CENTER, valign=Gtk.Align.END, hexpand=True) field_entry.set_size_request(150, 0) field_entry.connect("changed", self._on_update) self.fields.append(field_entry) self.widgets[field_entry] = (len(self.fields) - 1, 1, 1, 1) return field_entry def _create_del_btn(self): btn = Gtk.Button(label=_("Delete"), halign=Gtk.Align.CENTER, valign=Gtk.Align.START, hexpand=True) btn.set_size_request(150, 0) self.del_btns.append(btn) self.widgets[btn] = (len(self.del_btns) - 1, 2, 1, 1) btn.connect("clicked", self._clicked_del, len(self.del_btns) - 1) return btn def _clicked_add(self, *_args): self.component.__init__(self.collect_value() + [""], warn=False) self.show(self.component, editable=True) self.fields[len(self.component.args) - 1].grab_focus() def _clicked_del(self, _btn, pos): v = self.collect_value() v.pop(pos) self.component.__init__(v, warn=False) self.show(self.component, editable=True) self._on_update_callback() def show(self, component, editable=True): n = len(component.args) while len(self.fields) < n: self._create_field() self._create_del_btn() for i in range(n): field_entry = self.fields[i] with self.ignore_changes(): field_entry.set_text(component.args[i]) self.del_btns[i].show() self.widgets[self.add_btn] = (n + 1, 1, 1, 1) super().show(component, editable) for i in range(n, len(self.fields)): self.fields[i].hide() self.del_btns[i].hide() self.add_btn.set_valign(Gtk.Align.END if n >= 1 else Gtk.Align.CENTER) def collect_value(self): return [f.get_text() for f in self.fields if f.get_visible()] @classmethod def left_label(cls, component): return _("Execute") @classmethod def right_label(cls, component): return " ".join([shlex_quote(a) for a in component.args])
13,095
Python
.py
272
39.742647
127
0.630459
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,492
icons.py
pwr-Solaar_Solaar/lib/solaar/ui/icons.py
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/ ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import logging from gi.repository import Gtk import solaar.gtk as gtk logger = logging.getLogger(__name__) LARGE_SIZE = Gtk.IconSize.DIALOG # was 64 TRAY_INIT = "solaar-init" TRAY_OKAY = "solaar" TRAY_ATTENTION = "solaar-attention" _default_theme = None def _init_icon_paths(): global _default_theme if _default_theme: return _default_theme = Gtk.IconTheme.get_default() if logger.isEnabledFor(logging.DEBUG): logger.debug("icon theme paths: %s", _default_theme.get_search_path()) if gtk.battery_icons_style == "symbolic": global TRAY_OKAY TRAY_OKAY = TRAY_INIT # use monochrome tray icon if not _default_theme.has_icon("battery-good-symbolic"): logger.warning("failed to detect symbolic icons") gtk.battery_icons_style = "regular" if gtk.battery_icons_style == "regular": if not _default_theme.has_icon("battery-good"): logger.warning("failed to detect icons") gtk.battery_icons_style = "solaar" def battery(level=None, charging=False): icon_name = _battery_icon_name(level, charging) if not _default_theme.has_icon(icon_name): logger.warning("icon %s not found in current theme", icon_name) return TRAY_OKAY # use Solaar icon if battery icon not available elif logger.isEnabledFor(logging.DEBUG): logger.debug("battery icon for %s:%s = %s", level, charging, icon_name) return icon_name # return first res where val >= guard # _first_res(val,((guard,res),...)) def _first_res(val, pairs): return next((res for guard, res in pairs if val >= guard), None) def _battery_icon_name(level, charging): _init_icon_paths() if level is None or level < 0: return "battery-missing" + ("-symbolic" if gtk.battery_icons_style == "symbolic" else "") level_name = _first_res(level, ((90, "full"), (30, "good"), (20, "low"), (5, "caution"), (0, "empty"))) return "battery-%s%s%s" % ( level_name, "-charging" if charging else "", "-symbolic" if gtk.battery_icons_style == "symbolic" else "", ) def lux(level=None): if level is None or level < 0: return "light_unknown" return f"solaar-light_{int(20 * ((level + 50) // 100)):03}" _ICON_SETS = {} def device_icon_set(name="_", kind=None): icon_set = _ICON_SETS.get(name) if icon_set is None: # names of possible icons, in reverse desirability icon_set = ["preferences-desktop-peripherals"] if kind: if str(kind) == "numpad": icon_set += ("input-keyboard", "input-dialpad") elif str(kind) == "touchpad": icon_set += ("input-mouse", "input-tablet") elif str(kind) == "trackball": icon_set += ("input-mouse",) elif str(kind) == "headset": icon_set += ("audio-headphones", "audio-headset") icon_set += ("input-" + str(kind),) # icon_set += (name.replace(' ', '-'),) _ICON_SETS[name] = icon_set return icon_set def device_icon_file(name, kind=None, size=LARGE_SIZE): icon_name = device_icon_name(name, kind) return _default_theme.lookup_icon(icon_name, size, 0).get_filename() if icon_name is not None else None def device_icon_name(name, kind=None): _init_icon_paths() icon_set = device_icon_set(name, kind) assert icon_set for n in reversed(icon_set): if _default_theme.has_icon(n): return n def icon_file(name, size=LARGE_SIZE): _init_icon_paths() # has_icon() somehow returned False while lookup_icon returns non-None. # I guess it happens because share/solaar/icons/ has no hicolor and resolution subdirs theme_icon = _default_theme.lookup_icon(name, size, 0) if theme_icon: file_name = theme_icon.get_filename() return file_name logger.warning("icon %s(%d) not found in current theme", name, size)
4,801
Python
.py
106
39.367925
107
0.659593
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,493
presenter.py
pwr-Solaar_Solaar/lib/solaar/ui/about/presenter.py
## Copyright (C) Solaar Contributors ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from __future__ import annotations from typing_extensions import Protocol from solaar.ui.about.model import AboutModel class AboutViewProtocol(Protocol): def init_ui(self) -> None: ... def update_version_info(self, version: str) -> None: ... def update_description(self, comments: str) -> None: ... def update_copyright(self, copyright_text: str) -> None: ... def update_authors(self, authors: list[str]) -> None: ... def update_translators(self, translators: list[str]) -> None: ... def update_website(self, website): ... def update_credits(self, credit_sections: list[tuple[str, list[str]]]) -> None: ... def show(self) -> None: ... class Presenter: def __init__(self, model: AboutModel, view: AboutViewProtocol) -> None: self.model = model self.view = view def update_version_info(self) -> None: version = self.model.get_version() self.view.update_version_info(version) def update_credits(self) -> None: credit_sections = self.model.get_credit_sections() self.view.update_credits(credit_sections) def update_description(self) -> None: comments = self.model.get_description() self.view.update_description(comments) def update_copyright(self) -> None: copyright_text = self.model.get_copyright() self.view.update_copyright(copyright_text) def update_authors(self) -> None: authors = self.model.get_authors() self.view.update_authors(authors) def update_translators(self) -> None: translators = self.model.get_translators() self.view.update_translators(translators) def update_website(self) -> None: website = self.model.get_website() self.view.update_website(website) def run(self) -> None: self.view.init_ui() self.update_version_info() self.update_description() self.update_website() self.update_copyright() self.update_authors() self.update_credits() self.update_translators() self.view.show()
2,922
Python
.py
72
34.486111
83
0.675628
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,494
about.py
pwr-Solaar_Solaar/lib/solaar/ui/about/about.py
## Copyright (C) Solaar Contributors ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from solaar.ui.about.model import AboutModel from solaar.ui.about.presenter import Presenter from solaar.ui.about.view import AboutView def show(_=None, model=None, view=None): """Opens the About dialog.""" if model is None: model = AboutModel() if view is None: view = AboutView() presenter = Presenter(model, view) presenter.run() if __name__ == "__main__": from gi.repository import Gtk show(None) Gtk.main()
1,223
Python
.py
30
37.966667
74
0.737152
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,495
model.py
pwr-Solaar_Solaar/lib/solaar/ui/about/model.py
## Copyright (C) Solaar Contributors ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from __future__ import annotations from datetime import datetime from typing import List from typing import Tuple from solaar import __version__ from solaar.i18n import _ def _get_current_year() -> int: return datetime.now().year class AboutModel: def get_version(self) -> str: return __version__ def get_description(self) -> str: return _("Manages Logitech receivers,\nkeyboards, mice, and tablets.") def get_copyright(self) -> str: return f"© 2012-{_get_current_year()} Daniel Pavel and contributors to the Solaar project" def get_authors(self) -> List[str]: return [ "Daniel Pavel http://github.com/pwr", ] def get_translators(self) -> List[str]: return [ "gogo (croatian)", "Papoteur, David Geiger, Damien Lallement (français)", "Michele Olivo (italiano)", "Adrian Piotrowicz (polski)", "Drovetto, JrBenito (Portuguese-BR)", "Daniel Pavel (română)", "Daniel Zippert, Emelie Snecker (svensk)", "Dimitriy Ryazantcev (Russian)", "El Jinete Sin Cabeza (Español)", "Ferdina Kusumah (Indonesia)", ] def get_credit_sections(self) -> List[Tuple[str, List[str]]]: return [ (_("Additional Programming"), ["Filipe Laíns", "Peter F. Patel-Schneider"]), (_("GUI design"), ["Julien Gascard", "Daniel Pavel"]), ( _("Testing"), [ "Douglas Wagner", "Julien Gascard", "Peter Wu http://www.lekensteyn.nl/logitech-unifying.html", ], ), ( _("Logitech documentation"), [ "Julien Danjou http://julien.danjou.info/blog/2012/logitech-unifying-upower", "Nestor Lopez Casado http://drive.google.com/folderview?id=0BxbRzx7vEV7eWmgwazJ3NUFfQ28", ], ), ] def get_website(self): return "https://pwr-solaar.github.io/Solaar"
2,885
Python
.py
69
33.115942
109
0.616375
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,496
view.py
pwr-Solaar_Solaar/lib/solaar/ui/about/view.py
## Copyright (C) Solaar Contributors ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from typing import List from typing import Tuple from typing import Union from gi.repository import Gtk from solaar import NAME class AboutView: def __init__(self) -> None: self.view: Union[Gtk.AboutDialog, None] = None def init_ui(self) -> None: self.view = Gtk.AboutDialog() self.view.set_program_name(NAME) self.view.set_icon_name(NAME.lower()) self.view.set_license_type(Gtk.License.GPL_2_0) self.view.connect("response", lambda x, y: self.handle_close(x)) def update_version_info(self, version: str) -> None: self.view.set_version(version) def update_description(self, comments: str) -> None: self.view.set_comments(comments) def update_copyright(self, copyright_text: str): self.view.set_copyright(copyright_text) def update_authors(self, authors: List[str]) -> None: self.view.set_authors(authors) def update_credits(self, credit_sections: List[Tuple[str, List[str]]]) -> None: for section_name, people in credit_sections: self.view.add_credit_section(section_name, people) def update_translators(self, translators: List[str]) -> None: translator_credits = "\n".join(translators) self.view.set_translator_credits(translator_credits) def update_website(self, website): self.view.set_website_label(NAME) self.view.set_website(website) def show(self) -> None: self.view.present() def handle_close(self, event) -> None: event.hide()
2,302
Python
.py
50
40.86
83
0.709172
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,497
show.py
pwr-Solaar_Solaar/lib/solaar/cli/show.py
## Copyright (C) 2012-2013 Daniel Pavel ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from logitech_receiver import common from logitech_receiver import exceptions from logitech_receiver import hidpp10 from logitech_receiver import hidpp10_constants from logitech_receiver import hidpp20 from logitech_receiver import hidpp20_constants from logitech_receiver import receiver from logitech_receiver import settings_templates from logitech_receiver.common import LOGITECH_VENDOR_ID from logitech_receiver.common import NamedInt from logitech_receiver.common import strhex from logitech_receiver.hidpp20_constants import SupportedFeature from solaar import NAME from solaar import __version__ _hidpp10 = hidpp10.Hidpp10() _hidpp20 = hidpp20.Hidpp20() def _print_receiver(receiver): paired_count = receiver.count() print(receiver.name) print(" Device path :", receiver.path) print(f" USB id : {LOGITECH_VENDOR_ID:04x}:{receiver.product_id}") print(" Serial :", receiver.serial) pending = hidpp10.get_configuration_pending_flags(receiver) if pending: print(f" C Pending : {pending:02x}") if receiver.firmware: for f in receiver.firmware: print(" %-11s: %s" % (f.kind, f.version)) print(" Has", paired_count, f"paired device(s) out of a maximum of {int(receiver.max_devices)}.") if receiver.remaining_pairings() and receiver.remaining_pairings() >= 0: print(f" Has {int(receiver.remaining_pairings())} successful pairing(s) remaining.") notification_flags = _hidpp10.get_notification_flags(receiver) if notification_flags is not None: if notification_flags: notification_names = hidpp10_constants.NOTIFICATION_FLAG.flag_names(notification_flags) print(f" Notifications: {', '.join(notification_names)} (0x{notification_flags:06X})") else: print(" Notifications: (none)") activity = receiver.read_register(hidpp10_constants.Registers.DEVICES_ACTIVITY) if activity: activity = [(d, ord(activity[d - 1 : d])) for d in range(1, receiver.max_devices)] activity_text = ", ".join(f"{int(d)}={int(a)}" for d, a in activity if a > 0) print(" Device activity counters:", activity_text or "(empty)") def _battery_text(level) -> str: if level is None: return "N/A" elif isinstance(level, NamedInt): return str(level) else: return f"{int(level)}%" def _battery_line(dev): battery = dev.battery() if battery is not None: level, nextLevel, status, voltage = battery.level, battery.next_level, battery.status, battery.voltage text = _battery_text(level) if voltage is not None: text = text + f" {voltage}mV " nextText = "" if nextLevel is None else ", next level " + _battery_text(nextLevel) print(f" Battery: {text}, {status}{nextText}.") else: print(" Battery status unavailable.") def _print_device(dev, num=None): assert dev is not None # try to ping the device to see if it actually exists and to wake it up try: dev.ping() except exceptions.NoSuchDevice: print(f" {num}: Device not found" or dev.number) return if num or dev.number < 8: print(f" {int(num or dev.number)}: {dev.name}") else: print(f"{dev.name}") print(" Device path :", dev.path) if dev.wpid: print(f" WPID : {dev.wpid}") if dev.product_id: print(f" USB id : {LOGITECH_VENDOR_ID:04x}:{dev.product_id}") print(" Codename :", dev.codename) print(" Kind :", dev.kind) if dev.protocol: print(f" Protocol : HID++ {dev.protocol:1.1f}") else: print(" Protocol : unknown (device is offline)") if dev.polling_rate: print(" Report Rate :", dev.polling_rate) print(" Serial number:", dev.serial) if dev.modelId: print(" Model ID: ", dev.modelId) if dev.unitId: print(" Unit ID: ", dev.unitId) if dev.firmware: for fw in dev.firmware: print(f" {fw.kind:11}:", (fw.name + " " + fw.version).strip()) if dev.power_switch_location: print(f" The power switch is located on the {dev.power_switch_location}.") if dev.online: notification_flags = _hidpp10.get_notification_flags(dev) if notification_flags is not None: if notification_flags: notification_names = hidpp10_constants.NOTIFICATION_FLAG.flag_names(notification_flags) print(f" Notifications: {', '.join(notification_names)} (0x{notification_flags:06X}).") else: print(" Notifications: (none).") device_features = _hidpp10.get_device_features(dev) if device_features is not None: if device_features: device_features_names = hidpp10_constants.DEVICE_FEATURES.flag_names(device_features) print(f" Features: {', '.join(device_features_names)} (0x{device_features:06X})") else: print(" Features: (none)") if dev.online and dev.features: print(f" Supports {len(dev.features)} HID++ 2.0 features:") dev_settings = [] settings_templates.check_feature_settings(dev, dev_settings) for feature, index in dev.features.enumerate(): flags = dev.request(0x0000, feature.bytes(2)) flags = 0 if flags is None else ord(flags[1:2]) flags = common.flag_names(hidpp20_constants.FeatureFlag, flags) version = dev.features.get_feature_version(int(feature)) version = version if version else 0 print(" %2d: %-22s {%04X} V%s %s " % (index, feature, feature, version, ", ".join(flags))) if feature == SupportedFeature.HIRES_WHEEL: wheel = _hidpp20.get_hires_wheel(dev) if wheel: multi, has_invert, has_switch, inv, res, target, ratchet = wheel print(f" Multiplier: {multi}") if has_invert: print(" Has invert:", "Inverse wheel motion" if inv else "Normal wheel motion") if has_switch: print(" Has ratchet switch:", "Normal wheel mode" if ratchet else "Free wheel mode") if res: print(" High resolution mode") else: print(" Low resolution mode") if target: print(" HID++ notification") else: print(" HID notification") elif feature == SupportedFeature.MOUSE_POINTER: mouse_pointer = _hidpp20.get_mouse_pointer_info(dev) if mouse_pointer: print(f" DPI: {mouse_pointer['dpi']}") print(f" Acceleration: {mouse_pointer['acceleration']}") if mouse_pointer["suggest_os_ballistics"]: print(" Use OS ballistics") else: print(" Override OS ballistics") if mouse_pointer["suggest_vertical_orientation"]: print(" Provide vertical tuning, trackball") else: print(" No vertical tuning, standard mice") elif feature == SupportedFeature.VERTICAL_SCROLLING: vertical_scrolling_info = _hidpp20.get_vertical_scrolling_info(dev) if vertical_scrolling_info: print(f" Roller type: {vertical_scrolling_info['roller']}") print(f" Ratchet per turn: {vertical_scrolling_info['ratchet']}") print(f" Scroll lines: {vertical_scrolling_info['lines']}") elif feature == SupportedFeature.HI_RES_SCROLLING: scrolling_mode, scrolling_resolution = _hidpp20.get_hi_res_scrolling_info(dev) if scrolling_mode: print(" Hi-res scrolling enabled") else: print(" Hi-res scrolling disabled") if scrolling_resolution: print(f" Hi-res scrolling multiplier: {scrolling_resolution}") elif feature == SupportedFeature.POINTER_SPEED: pointer_speed = _hidpp20.get_pointer_speed_info(dev) if pointer_speed: print(f" Pointer Speed: {pointer_speed}") elif feature == SupportedFeature.LOWRES_WHEEL: wheel_status = _hidpp20.get_lowres_wheel_status(dev) if wheel_status: print(f" Wheel Reports: {wheel_status}") elif feature == SupportedFeature.NEW_FN_INVERSION: inversion = _hidpp20.get_new_fn_inversion(dev) if inversion: inverted, default_inverted = inversion print(" Fn-swap:", "enabled" if inverted else "disabled") print(" Fn-swap default:", "enabled" if default_inverted else "disabled") elif feature == SupportedFeature.HOSTS_INFO: host_names = _hidpp20.get_host_names(dev) for host, (paired, name) in host_names.items(): print(f" Host {host} ({'paired' if paired else 'unpaired'}): {name}") elif feature == SupportedFeature.DEVICE_NAME: print(f" Name: {_hidpp20.get_name(dev)}") print(f" Kind: {_hidpp20.get_kind(dev)}") elif feature == SupportedFeature.DEVICE_FRIENDLY_NAME: print(f" Friendly Name: {_hidpp20.get_friendly_name(dev)}") elif feature == SupportedFeature.DEVICE_FW_VERSION: for fw in _hidpp20.get_firmware(dev): extras = strhex(fw.extras) if fw.extras else "" print(f" Firmware: {fw.kind} {fw.name} {fw.version} {extras}") ids = _hidpp20.get_ids(dev) if ids: unitId, modelId, tid_map = ids print(f" Unit ID: {unitId} Model ID: {modelId} Transport IDs: {tid_map}") elif feature == SupportedFeature.REPORT_RATE or feature == SupportedFeature.EXTENDED_ADJUSTABLE_REPORT_RATE: print(f" Report Rate: {_hidpp20.get_polling_rate(dev)}") elif feature == SupportedFeature.CONFIG_CHANGE: response = dev.feature_request(SupportedFeature.CONFIG_CHANGE, 0x00) print(f" Configuration: {response.hex()}") elif feature == SupportedFeature.REMAINING_PAIRING: print(f" Remaining Pairings: {int(_hidpp20.get_remaining_pairing(dev))}") elif feature == SupportedFeature.ONBOARD_PROFILES: if _hidpp20.get_onboard_mode(dev) == hidpp20_constants.ONBOARD_MODES.MODE_HOST: mode = "Host" else: mode = "On-Board" print(f" Device Mode: {mode}") elif hidpp20.battery_functions.get(feature, None): print("", end=" ") _battery_line(dev) for setting in dev_settings: if setting.feature == feature: if ( setting._device and getattr(setting._device, "persister", None) and setting._device.persister.get(setting.name) is not None ): v = setting.val_to_string(setting._device.persister.get(setting.name)) print(f" {setting.label} (saved): {v}") try: v = setting.val_to_string(setting.read(False)) except exceptions.FeatureCallError as e: v = "HID++ error " + str(e) except AssertionError as e: v = "AssertionError " + str(e) print(f" {setting.label} : {v}") if dev.online and dev.keys: print(f" Has {len(dev.keys)} reprogrammable keys:") for k in dev.keys: # TODO: add here additional variants for other REPROG_CONTROLS if dev.keys.keyversion == SupportedFeature.REPROG_CONTROLS_V2: print(" %2d: %-26s => %-27s %s" % (k.index, k.key, k.default_task, ", ".join(k.flags))) if dev.keys.keyversion == SupportedFeature.REPROG_CONTROLS_V4: print(" %2d: %-26s, default: %-27s => %-26s" % (k.index, k.key, k.default_task, k.mapped_to)) gmask_fmt = ",".join(k.group_mask) gmask_fmt = gmask_fmt if gmask_fmt else "empty" print(f" {', '.join(k.flags)}, pos:{int(k.pos)}, group:{int(k.group):1}, group mask:{gmask_fmt}") report_fmt = ", ".join(k.mapping_flags) report_fmt = report_fmt if report_fmt else "default" print(f" reporting: {report_fmt}") if dev.online and dev.remap_keys: print(f" Has {len(dev.remap_keys)} persistent remappable keys:") for k in dev.remap_keys: print(" %2d: %-26s => %s%s" % (k.index, k.key, k.action, " (remapped)" if k.cidStatus else "")) if dev.online and dev.gestures: print( " Has %d gesture(s), %d param(s) and %d spec(s):" % (len(dev.gestures.gestures), len(dev.gestures.params), len(dev.gestures.specs)) ) for k in dev.gestures.gestures.values(): print( " %-26s Enabled(%4s): %-5s Diverted:(%4s) %s" % (k.gesture, k.index, k.enabled(), k.diversion_index, k.diverted()) ) for k in dev.gestures.params.values(): print(" %-26s Value (%4s): %s [Default: %s]" % (k.param, k.index, k.value, k.default_value)) for k in dev.gestures.specs.values(): print(" %-26s Spec (%4s): %s" % (k.spec, k.id, k.value)) if dev.online: _battery_line(dev) else: print(" Battery: unknown (device is offline).") def run(devices, args, find_receiver, find_device): assert devices assert args.device print(f"{NAME.lower()} version {__version__}") print("") device_name = args.device.lower() if device_name == "all": for d in devices: if isinstance(d, receiver.Receiver): _print_receiver(d) count = d.count() if count: for dev in d: print("") _print_device(dev, dev.number) count -= 1 if not count: break print("") else: print("") _print_device(d) return dev = find_receiver(devices, device_name) if dev and not dev.isDevice: _print_receiver(dev) return dev = next(find_device(devices, device_name), None) if not dev: raise Exception(f"no device found matching '{device_name}'") _print_device(dev)
16,386
Python
.py
311
40.536977
125
0.559419
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,498
config.py
pwr-Solaar_Solaar/lib/solaar/cli/config.py
## Copyright (C) 2012-2013 Daniel Pavel ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import yaml from logitech_receiver import settings from logitech_receiver import settings_templates from logitech_receiver.common import NamedInts from solaar import configuration APP_ID = "io.github.pwr_solaar.solaar" def _print_setting(s, verbose=True): print("#", s.label) if verbose: if s.description: print("#", s.description.replace("\n", " ")) if s.kind == settings.KIND.toggle: print("# possible values: on/true/t/yes/y/1 or off/false/f/no/n/0 or Toggle/~") elif s.kind == settings.KIND.choice: print( "# possible values: one of [", ", ".join(str(v) for v in s.choices), "], or higher/lower/highest/max/lowest/min", ) else: # wtf? pass value = s.read(cached=False) if value is None: print(s.name, "= ? (failed to read from device)") else: print(s.name, "=", s.val_to_string(value)) def _print_setting_keyed(s, key, verbose=True): print("#", s.label) if verbose: if s.description: print("#", s.description.replace("\n", " ")) if s.kind == settings.KIND.multiple_toggle: k = next((k for k in s._labels if key == k), None) if k is None: print(s.name, "=? (key not found)") else: print("# possible values: on/true/t/yes/y/1 or off/false/f/no/n/0 or Toggle/~") value = s.read(cached=False) if value is None: print(s.name, "= ? (failed to read from device)") else: print(s.name, s.val_to_string({k: value[str(int(k))]})) elif s.kind == settings.KIND.map_choice: k = next((k for k in s.choices.keys() if key == k), None) if k is None: print(s.name, "=? (key not found)") else: print("# possible values: one of [", ", ".join(str(v) for v in s.choices[k]), "]") value = s.read(cached=False) if value is None: print(s.name, "= ? (failed to read from device)") else: print(s.name, s.val_to_string({k: value[int(k)]})) def to_int(s): try: return int(s) except ValueError: return None def select_choice(value, choices, setting, key): lvalue = value.lower() ivalue = to_int(value) val = None for choice in choices: if value == str(choice): val = choice break if val is not None: value = val elif ivalue is not None and 1 <= ivalue <= len(choices): value = choices[ivalue - 1] elif lvalue in ("higher", "lower"): old_value = setting.read() if key is None else setting.read_key(key) if old_value is None: raise Exception(f"{setting.name}: could not read current value") if lvalue == "lower": lower_values = choices[:old_value] value = lower_values[-1] if lower_values else choices[:][0] elif lvalue == "higher": higher_values = choices[old_value + 1 :] value = higher_values[0] if higher_values else choices[:][-1] elif lvalue in ("highest", "max", "first"): value = choices[:][-1] elif lvalue in ("lowest", "min", "last"): value = choices[:][0] else: raise Exception(f"{setting.name}: possible values are [{', '.join(str(v) for v in choices)}]") return value def select_toggle(value, setting, key=None): if value.lower() in ("toggle", "~"): value = not (setting.read() if key is None else setting.read()[str(int(key))]) else: try: value = bool(int(value)) except Exception as exc: if value.lower() in ("true", "yes", "on", "t", "y"): value = True elif value.lower() in ("false", "no", "off", "f", "n"): value = False else: raise Exception(f"{setting.name}: don't know how to interpret '{value}' as boolean") from exc return value def select_range(value, setting): try: value = int(value) except ValueError as exc: raise Exception(f"{setting.name}: can't interpret '{value}' as integer") from exc minimum, maximum = setting.range if value < minimum or value > maximum: raise Exception(f"{setting.name}: value '{value}' out of bounds") return value def run(receivers, args, _find_receiver, find_device): assert receivers assert args.device device_name = args.device.lower() dev = None for dev in find_device(receivers, device_name): if dev.ping(): break dev = None if not dev: raise Exception(f"no online device found matching '{device_name}'") if not args.setting: # print all settings, so first set them all up if not dev.settings: raise Exception(f"no settings for {dev.name}") configuration.attach_to(dev) print(dev.name, f"({dev.codename}) [{dev.wpid}:{dev.serial}]") for s in dev.settings: print("") _print_setting(s) return setting_name = args.setting.lower() setting = settings_templates.check_feature_setting(dev, setting_name) if not setting and dev.descriptor and dev.descriptor.settings: for sclass in dev.descriptor.settings: if sclass.register and sclass.name == setting_name: try: setting = sclass.build(dev) except Exception: setting = None if setting is None: raise Exception(f"no setting '{args.setting}' for {dev.name}") if args.value_key is None: _print_setting(setting) return remote = False try: import gi gi.require_version("Gtk", "3.0") from gi.repository import Gio from gi.repository import Gtk if Gtk.init_check()[0]: # can Gtk be initialized? application = Gtk.Application.new(APP_ID, Gio.ApplicationFlags.HANDLES_COMMAND_LINE) application.register() remote = application.get_is_remote() except Exception: pass # don't save configuration here because we might want the Solaar GUI to make the change result, message, value = set(dev, setting, args, False) if message is not None: print(message) if result is None: raise Exception(f"{setting.name}: failed to set value '{str(value)}' [{value!r}]") # if the Solaar UI is running tell it to also perform the set, otherwise save the change in the configuration file if remote: argl = ["config", dev.serial or dev.unitId, setting.name] argl.extend([a for a in [args.value_key, args.extra_subkey, args.extra2] if a is not None]) application.run(yaml.safe_dump(argl)) else: if dev.persister and setting.persist: dev.persister[setting.name] = setting._value def set(dev, setting, args, save): if setting.kind == settings.KIND.toggle: value = select_toggle(args.value_key, setting) args.value_key = value message = f"Setting {setting.name} of {dev.name} to {value}" result = setting.write(value, save=save) elif setting.kind == settings.KIND.range: value = select_range(args.value_key, setting) args.value_key = value message = f"Setting {setting.name} of {dev.name} to {value}" result = setting.write(value, save=save) elif setting.kind == settings.KIND.choice: value = select_choice(args.value_key, setting.choices, setting, None) args.value_key = int(value) message = f"Setting {setting.name} of {dev.name} to {value}" result = setting.write(value, save=save) elif setting.kind == settings.KIND.map_choice: if args.extra_subkey is None: _print_setting_keyed(setting, args.value_key) return None, None, None key = args.value_key ikey = to_int(key) k = next((k for k in setting.choices.keys() if key == k), None) if k is None and ikey is not None: k = next((k for k in setting.choices.keys() if ikey == k), None) if k is not None: value = select_choice(args.extra_subkey, setting.choices[k], setting, key) args.extra_subkey = int(value) args.value_key = str(int(k)) else: raise Exception(f"{setting.name}: key '{key}' not in setting") message = f"Setting {setting.name} of {dev.name} key {k!r} to {value!r}" result = setting.write_key_value(int(k), value, save=save) elif setting.kind == settings.KIND.multiple_toggle: if args.extra_subkey is None: _print_setting_keyed(setting, args.value_key) return None, None, None key = args.value_key all_keys = getattr(setting, "choices_universe", None) ikey = all_keys[int(key) if key.isdigit() else key] if isinstance(all_keys, NamedInts) else to_int(key) k = next((k for k in setting._labels if key == k), None) if k is None and ikey is not None: k = next((k for k in setting._labels if ikey == k), None) if k is not None: value = select_toggle(args.extra_subkey, setting, key=k) args.extra_subkey = value args.value_key = str(int(k)) else: raise Exception(f"{setting.name}: key '{key}' not in setting") message = f"Setting {setting.name} key {k!r} to {value!r}" result = setting.write_key_value(str(int(k)), value, save=save) elif setting.kind == settings.KIND.multiple_range: if args.extra_subkey is None: raise Exception(f"{setting.name}: setting needs both key and value to set") key = args.value_key all_keys = getattr(setting, "choices_universe", None) ikey = all_keys[int(key) if key.isdigit() else key] if isinstance(all_keys, NamedInts) else to_int(key) if args.extra2 is None or to_int(args.extra2) is None: raise Exception(f"{setting.name}: setting needs an integer value, not {args.extra2}") if not setting._value: # ensure that there are values to look through setting.read() k = next((k for k in setting._value if key == ikey or key.isdigit() and ikey == int(key)), None) if k is None and ikey is not None: k = next((k for k in setting._value if ikey == k), None) item = setting._value[k] if args.extra_subkey in item.keys(): item[args.extra_subkey] = to_int(args.extra2) args.value_key = str(int(k)) else: raise Exception(f"{setting.name}: key '{key}' not in setting") message = f"Setting {setting.name} key {k} parameter {args.extra_subkey} to {item[args.extra_subkey]!r}" result = setting.write_key_value(int(k), item, save=save) value = item else: raise Exception("NotImplemented") return result, message, value
11,915
Python
.py
262
36.423664
118
0.604563
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)
20,499
pair.py
pwr-Solaar_Solaar/lib/solaar/cli/pair.py
## Copyright (C) 2012-2013 Daniel Pavel ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License along ## with this program; if not, write to the Free Software Foundation, Inc., ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from time import time from logitech_receiver import base from logitech_receiver import hidpp10 from logitech_receiver import hidpp10_constants from logitech_receiver import notifications _hidpp10 = hidpp10.Hidpp10() def run(receivers, args, find_receiver, _ignore): assert receivers if args.receiver: receiver_name = args.receiver.lower() receiver = find_receiver(receivers, receiver_name) if not receiver: raise Exception(f"no receiver found matching '{receiver_name}'") else: receiver = receivers[0] assert receiver # check if it's necessary to set the notification flags old_notification_flags = _hidpp10.get_notification_flags(receiver) or 0 if not (old_notification_flags & hidpp10_constants.NOTIFICATION_FLAG.wireless): _hidpp10.set_notification_flags(receiver, old_notification_flags | hidpp10_constants.NOTIFICATION_FLAG.wireless) # get all current devices known_devices = [dev.number for dev in receiver] class _HandleWithNotificationHook(int): def notifications_hook(self, n): nonlocal known_devices assert n if n.devnumber == 0xFF: notifications.process(receiver, n) elif n.sub_id == 0x41 and len(n.data) == base.SHORT_MESSAGE_SIZE - 4: kd, known_devices = known_devices, None # only process one connection notification if kd is not None: if n.devnumber not in kd: receiver.pairing.new_device = receiver.register_new_device(n.devnumber, n) elif receiver.re_pairs: del receiver[n.devnumber] # get rid of information on device re-paired away receiver.pairing.new_device = receiver.register_new_device(n.devnumber, n) timeout = 30 # seconds receiver.handle = _HandleWithNotificationHook(receiver.handle) if receiver.receiver_kind == "bolt": # Bolt receivers require authentication to pair a device receiver.discover(timeout=timeout) print("Bolt Pairing: long-press the pairing key or button on your device (timing out in", timeout, "seconds).") pairing_start = time() patience = 5 # the discovering notification may come slightly later, so be patient while receiver.pairing.discovering or time() - pairing_start < patience: if receiver.pairing.device_address and receiver.pairing.device_authentication and receiver.pairing.device_name: break n = base.read(receiver.handle) n = base.make_notification(*n) if n else None if n: receiver.handle.notifications_hook(n) address = receiver.pairing.device_address name = receiver.pairing.device_name authentication = receiver.pairing.device_authentication kind = receiver.pairing.device_kind print(f"Bolt Pairing: discovered {name}") receiver.pair_device( address=address, authentication=authentication, entropy=20 if kind == hidpp10_constants.DEVICE_KIND.keyboard else 10, ) pairing_start = time() patience = 5 # the discovering notification may come slightly later, so be patient while receiver.pairing.lock_open or time() - pairing_start < patience: if receiver.pairing.device_passkey: break n = base.read(receiver.handle) n = base.make_notification(*n) if n else None if n: receiver.handle.notifications_hook(n) if authentication & 0x01: print(f"Bolt Pairing: type passkey {receiver.pairing.device_passkey} and then press the enter key") else: passkey = f"{int(receiver.pairing.device_passkey):010b}" passkey = ", ".join(["right" if bit == "1" else "left" for bit in passkey]) print(f"Bolt Pairing: press {passkey}") print("and then press left and right buttons simultaneously") while receiver.pairing.lock_open: n = base.read(receiver.handle) n = base.make_notification(*n) if n else None if n: receiver.handle.notifications_hook(n) else: receiver.set_lock(False, timeout=timeout) print("Pairing: Turn your device on or press, hold, and release") print("a channel button or the channel switch button.") print("Timing out in", timeout, "seconds.") pairing_start = time() patience = 5 # the lock-open notification may come slightly later, wait for it a bit while receiver.pairing.lock_open or time() - pairing_start < patience: n = base.read(receiver.handle) if n: n = base.make_notification(*n) if n: receiver.handle.notifications_hook(n) if not (old_notification_flags & hidpp10_constants.NOTIFICATION_FLAG.wireless): # only clear the flags if they weren't set before, otherwise a # concurrently running Solaar app might stop working properly _hidpp10.set_notification_flags(receiver, old_notification_flags) if receiver.pairing.new_device: dev = receiver.pairing.new_device print(f"Paired device {int(dev.number)}: {dev.name} ({dev.codename}) [{dev.wpid}:{dev.serial}]") else: error = receiver.pairing.error if error: raise Exception(f"pairing failed: {error}") else: print("Paired device") # this is better than an error
6,369
Python
.py
122
42.819672
123
0.663832
pwr-Solaar/Solaar
5,327
400
31
GPL-2.0
9/5/2024, 5:12:46 PM (Europe/Amsterdam)