INSTRUCTION
stringlengths 1
46.3k
| RESPONSE
stringlengths 75
80.2k
|
|---|---|
Create features for all possible country labels, return as matrix for keras.
Parameters
----------
loc: dict
one entry from the list of locations and features that come out of make_country_features
Returns
--------
keras_inputs: dict with two keys, "label" and "matrix"
|
def make_country_matrix(self, loc):
"""
Create features for all possible country labels, return as matrix for keras.
Parameters
----------
loc: dict
one entry from the list of locations and features that come out of make_country_features
Returns
--------
keras_inputs: dict with two keys, "label" and "matrix"
"""
top = loc['features']['ct_mention']
top_count = loc['features']['ctm_count1']
two = loc['features']['ct_mention2']
two_count = loc['features']['ctm_count2']
word_vec = loc['features']['word_vec']
first_back = loc['features']['first_back']
most_alt = loc['features']['most_alt']
most_pop = loc['features']['most_pop']
possible_labels = set([top, two, word_vec, first_back, most_alt, most_pop])
possible_labels = [i for i in possible_labels if i]
X_mat = []
for label in possible_labels:
inputs = np.array([word_vec, first_back, most_alt, most_pop])
x = inputs == label
x = np.asarray((x * 2) - 1) # convert to -1, 1
# get missing values
exists = inputs != ""
exists = np.asarray((exists * 2) - 1)
counts = np.asarray([top_count, two_count]) # cludgy, should be up with "inputs"
right = np.asarray([top, two]) == label
right = right * 2 - 1
right[counts == 0] = 0
# get correct values
features = np.concatenate([x, exists, counts, right])
X_mat.append(np.asarray(features))
keras_inputs = {"labels": possible_labels,
"matrix" : np.asmatrix(X_mat)}
return keras_inputs
|
NLP a doc, find its entities, get their features, and return the model's country guess for each.
Maybe use a better name.
Parameters
-----------
doc: str or spaCy
the document to country-resolve the entities in
Returns
-------
proced: list of dict
the feature output of "make_country_features" updated with the model's
estimated country for each entity.
E.g.:
{'all_confidence': array([ 0.95783567, 0.03769876, 0.00454875], dtype=float32),
'all_countries': array(['SYR', 'USA', 'JAM'], dtype='<U3'),
'country_conf': 0.95783567,
'country_predicted': 'SYR',
'features': {'ct_mention': '',
'ct_mention2': '',
'ctm_count1': 0,
'ctm_count2': 0,
'first_back': 'JAM',
'maj_vote': 'SYR',
'most_alt': 'USA',
'most_pop': 'SYR',
'word_vec': 'SYR',
'wv_confid': '29.3188'},
'label': 'Syria',
'spans': [{'end': 26, 'start': 20}],
'text': "There's fighting in Aleppo and Homs.",
'word': 'Aleppo'}
|
def infer_country(self, doc):
"""NLP a doc, find its entities, get their features, and return the model's country guess for each.
Maybe use a better name.
Parameters
-----------
doc: str or spaCy
the document to country-resolve the entities in
Returns
-------
proced: list of dict
the feature output of "make_country_features" updated with the model's
estimated country for each entity.
E.g.:
{'all_confidence': array([ 0.95783567, 0.03769876, 0.00454875], dtype=float32),
'all_countries': array(['SYR', 'USA', 'JAM'], dtype='<U3'),
'country_conf': 0.95783567,
'country_predicted': 'SYR',
'features': {'ct_mention': '',
'ct_mention2': '',
'ctm_count1': 0,
'ctm_count2': 0,
'first_back': 'JAM',
'maj_vote': 'SYR',
'most_alt': 'USA',
'most_pop': 'SYR',
'word_vec': 'SYR',
'wv_confid': '29.3188'},
'label': 'Syria',
'spans': [{'end': 26, 'start': 20}],
'text': "There's fighting in Aleppo and Homs.",
'word': 'Aleppo'}
"""
if not hasattr(doc, "ents"):
doc = nlp(doc)
proced = self.make_country_features(doc, require_maj=False)
if not proced:
pass
# logging!
#print("Nothing came back from make_country_features")
feat_list = []
#proced = self.ent_list_to_matrix(proced)
for loc in proced:
feat = self.make_country_matrix(loc)
#labels = loc['labels']
feat_list.append(feat)
#try:
# for each potential country...
for n, i in enumerate(feat_list):
labels = i['labels']
try:
prediction = self.country_model.predict(i['matrix']).transpose()[0]
ranks = prediction.argsort()[::-1]
labels = np.asarray(labels)[ranks]
prediction = prediction[ranks]
except ValueError:
prediction = np.array([0])
labels = np.array([""])
loc['country_predicted'] = labels[0]
loc['country_conf'] = prediction[0]
loc['all_countries'] = labels
loc['all_confidence'] = prediction
return proced
|
Convert a geonames admin1 code to the associated place name.
Parameters
---------
country_code2: string
The two character country code
admin1_code: string
The admin1 code to be converted. (Admin1 is the highest
subnational political unit, state/region/provice/etc.
admin1_dict: dictionary
The dictionary containing the country code + admin1 code
as keys and the admin1 names as values.
Returns
------
admin1_name: string
The admin1 name. If none is found, return "NA".
|
def get_admin1(self, country_code2, admin1_code):
"""
Convert a geonames admin1 code to the associated place name.
Parameters
---------
country_code2: string
The two character country code
admin1_code: string
The admin1 code to be converted. (Admin1 is the highest
subnational political unit, state/region/provice/etc.
admin1_dict: dictionary
The dictionary containing the country code + admin1 code
as keys and the admin1 names as values.
Returns
------
admin1_name: string
The admin1 name. If none is found, return "NA".
"""
lookup_key = ".".join([country_code2, admin1_code])
try:
admin1_name = self._admin1_dict[lookup_key]
return admin1_name
except KeyError:
#print("No admin code found for country {} and code {}".format(country_code2, admin1_code))
return "NA"
|
Compute features for ranking results from ES/geonames
Parameters
----------
proc : dict
One dictionary from the list that comes back from geoparse or from make_country_features (doesn't matter)
results : dict
the response from a geonames query
Returns
--------
X : numpy matrix
holding the computed features
meta: list of dicts
including feature information
|
def features_for_rank(self, proc, results):
"""Compute features for ranking results from ES/geonames
Parameters
----------
proc : dict
One dictionary from the list that comes back from geoparse or from make_country_features (doesn't matter)
results : dict
the response from a geonames query
Returns
--------
X : numpy matrix
holding the computed features
meta: list of dicts
including feature information
"""
feature_list = []
meta = []
results = results['hits']['hits']
search_name = proc['word']
code_mention = proc['features']['code_mention']
class_mention = proc['features']['class_mention']
for rank, entry in enumerate(results):
# go through the results and calculate some features
# get population number and exists
try:
pop = int(entry['population'])
has_pop = 1
except Exception as e:
pop = 0
has_pop = 0
if pop > 0:
logp = np.log(pop)
else:
logp = 0
### order the results came back
adj_rank = 1 / np.log(rank + 2)
# alternative names
len_alt = len(entry['alternativenames'])
adj_alt = np.log(len_alt)
### feature class (just boost the good ones)
if entry['feature_class'] == "A" or entry['feature_class'] == "P":
good_type = 1
else:
good_type = 0
#fc_score = 3
### feature class/code matching
if entry['feature_class'] == class_mention:
good_class_mention = 1
else:
good_class_mention = 0
if entry['feature_code'] == code_mention:
good_code_mention = 1
else:
good_code_mention = 0
### edit distance
ed = editdistance.eval(search_name, entry['name'])
ed = ed # shrug
# maybe also get min edit distance to alternative names...
features = [has_pop, pop, logp, adj_rank, len_alt, adj_alt,
good_type, good_class_mention, good_code_mention, ed]
m = self.format_geonames(entry)
feature_list.append(features)
meta.append(m)
#meta = geo.format_geonames(results)
X = np.asmatrix(feature_list)
return (X, meta)
|
Sort the place features list by the score of its relevance.
|
def ranker(self, X, meta):
"""
Sort the place features list by the score of its relevance.
"""
# total score is just a sum of each row
total_score = X.sum(axis=1).transpose()
total_score = np.squeeze(np.asarray(total_score)) # matrix to array
ranks = total_score.argsort()
ranks = ranks[::-1]
# sort the list of dicts according to ranks
sorted_meta = [meta[r] for r in ranks]
sorted_X = X[ranks]
return (sorted_X, sorted_meta)
|
Given a feature matrix, geonames data, and the original query,
construct a prodigy task.
Make meta nicely readable: "A town in Germany"
Parameters
----------
X: matrix
vector of features for ranking. Output of features_for_rank()
meta: list of dictionaries
other place information. Output of features_for_rank(). Used to provide
information like "city in Germany" to the coding task.
placename: str
The extracted place name from text
Returns
--------
task_list: list of dicts
Tasks ready to be written to JSONL and use in Prodigy. Each potential match includes
a text description to the annotator can pick the right one.
|
def format_for_prodigy(self, X, meta, placename, return_feature_subset=False):
"""
Given a feature matrix, geonames data, and the original query,
construct a prodigy task.
Make meta nicely readable: "A town in Germany"
Parameters
----------
X: matrix
vector of features for ranking. Output of features_for_rank()
meta: list of dictionaries
other place information. Output of features_for_rank(). Used to provide
information like "city in Germany" to the coding task.
placename: str
The extracted place name from text
Returns
--------
task_list: list of dicts
Tasks ready to be written to JSONL and use in Prodigy. Each potential match includes
a text description to the annotator can pick the right one.
"""
all_tasks = []
sorted_X, sorted_meta = self.ranker(X, meta)
sorted_meta = sorted_meta[:4]
sorted_X = sorted_X[:4]
for n, i in enumerate(sorted_meta):
feature_code = i['feature_code']
try:
fc = self._code_to_text[feature_code]
except KeyError:
fc = ''
text = ''.join(['"', i['place_name'], '"',
", a ", fc,
" in ", i['country_code3'],
", id: ", i['geonameid']])
d = {"id" : n + 1, "text" : text}
all_tasks.append(d)
if return_feature_subset:
return (all_tasks, sorted_meta, sorted_X)
else:
return all_tasks
|
Pull out just the fields we want from a geonames entry
To do:
- switch to model picking
Parameters
-----------
res : dict
ES/geonames result
searchterm : str
(not implemented). Needed for better results picking
Returns
--------
new_res : dict
containing selected fields from selected geonames entry
|
def format_geonames(self, entry, searchterm=None):
"""
Pull out just the fields we want from a geonames entry
To do:
- switch to model picking
Parameters
-----------
res : dict
ES/geonames result
searchterm : str
(not implemented). Needed for better results picking
Returns
--------
new_res : dict
containing selected fields from selected geonames entry
"""
try:
lat, lon = entry['coordinates'].split(",")
new_res = {"admin1" : self.get_admin1(entry['country_code2'], entry['admin1_code']),
"lat" : lat,
"lon" : lon,
"country_code3" : entry["country_code3"],
"geonameid" : entry["geonameid"],
"place_name" : entry["name"],
"feature_class" : entry["feature_class"],
"feature_code" : entry["feature_code"]}
return new_res
except (IndexError, TypeError):
# two conditions for these errors:
# 1. there are no results for some reason (Index)
# 2. res is set to "" because the country model was below the thresh
new_res = {"admin1" : "",
"lat" : "",
"lon" : "",
"country_code3" : "",
"geonameid" : "",
"place_name" : "",
"feature_class" : "",
"feature_code" : ""}
return new_res
|
Small helper function to delete the features from the final dictionary.
These features are mostly interesting for debugging but won't be relevant for most users.
|
def clean_proced(self, proced):
"""Small helper function to delete the features from the final dictionary.
These features are mostly interesting for debugging but won't be relevant for most users.
"""
for loc in proced:
try:
del loc['all_countries']
except KeyError:
pass
try:
del loc['matrix']
except KeyError:
pass
try:
del loc['all_confidence']
except KeyError:
pass
try:
del loc['place_confidence']
except KeyError:
pass
try:
del loc['text']
except KeyError:
pass
try:
del loc['label']
except KeyError:
pass
try:
del loc['features']
except KeyError:
pass
return proced
|
Main geoparsing function. Text to extracted, resolved entities.
Parameters
----------
doc : str or spaCy
The document to be geoparsed. Can be either raw text or already spacy processed.
In some cases, it makes sense to bulk parse using spacy's .pipe() before sending
through to Mordecai
Returns
-------
proced : list of dicts
Each entity gets an entry in the list, with the dictionary including geo info, spans,
and optionally, the input features.
|
def geoparse(self, doc, verbose=False):
"""Main geoparsing function. Text to extracted, resolved entities.
Parameters
----------
doc : str or spaCy
The document to be geoparsed. Can be either raw text or already spacy processed.
In some cases, it makes sense to bulk parse using spacy's .pipe() before sending
through to Mordecai
Returns
-------
proced : list of dicts
Each entity gets an entry in the list, with the dictionary including geo info, spans,
and optionally, the input features.
"""
if not hasattr(doc, "ents"):
doc = nlp(doc)
proced = self.infer_country(doc)
if not proced:
return []
# logging!
#print("Nothing came back from infer_country...")
if self.threads:
pool = ThreadPool(len(proced))
results = pool.map(self.proc_lookup_country, proced)
pool.close()
pool.join()
else:
results = []
for loc in proced:
# if the confidence is too low, don't use the country info
if loc['country_conf'] > self.country_threshold:
res = self.query_geonames_country(loc['word'], loc['country_predicted'])
results.append(res)
else:
results.append("")
for n, loc in enumerate(proced):
res = results[n]
try:
_ = res['hits']['hits']
# If there's no geonames result, what to do?
# For now, just continue.
# In the future, delete? Or add an empty "loc" field?
except (TypeError, KeyError):
continue
# Pick the best place
X, meta = self.features_for_rank(loc, res)
if X.shape[1] == 0:
# This happens if there are no results...
continue
all_tasks, sorted_meta, sorted_X = self.format_for_prodigy(X, meta, loc['word'], return_feature_subset=True)
fl_pad = np.pad(sorted_X, ((0, 4 - sorted_X.shape[0]), (0, 0)), 'constant')
fl_unwrap = fl_pad.flatten()
prediction = self.rank_model.predict(np.asmatrix(fl_unwrap))
place_confidence = prediction.max()
loc['geo'] = sorted_meta[prediction.argmax()]
loc['place_confidence'] = place_confidence
if not verbose:
proced = self.clean_proced(proced)
return proced
|
Batch geoparsing function. Take in a list of text documents and return a list of lists
of the geoparsed documents. The speed improvements come exclusively from using spaCy's `nlp.pipe`.
Parameters
----------
text_list : list of strs
List of documents. The documents should not have been pre-processed by spaCy.
Returns
-------
processed : list of list of dictionaries.
The list is the same length as the input list of documents. Each element is a list of dicts, one for
each geolocated entity.
|
def batch_geoparse(self, text_list):
"""
Batch geoparsing function. Take in a list of text documents and return a list of lists
of the geoparsed documents. The speed improvements come exclusively from using spaCy's `nlp.pipe`.
Parameters
----------
text_list : list of strs
List of documents. The documents should not have been pre-processed by spaCy.
Returns
-------
processed : list of list of dictionaries.
The list is the same length as the input list of documents. Each element is a list of dicts, one for
each geolocated entity.
"""
if not self.threads:
print("batch_geoparsed should be used with threaded searches. Please set `threads=True` when initializing the geoparser.")
nlped_docs = list(nlp.pipe(text_list, as_tuples=False, n_threads=multiprocessing.cpu_count()))
processed = []
for i in tqdm(nlped_docs, disable=not self.progress):
p = self.geoparse(i)
processed.append(p)
return processed
|
Take in a line from the labeled json and return a vector of labels and a matrix of features
for training.
Two ways to get 0s:
- marked as false by user
- generated automatically from other entries when guess is correct
Rather than iterating through entities, just get the number of the correct entity directly.
Then get one or two GPEs before and after.
|
def entry_to_matrix(prodigy_entry):
"""
Take in a line from the labeled json and return a vector of labels and a matrix of features
for training.
Two ways to get 0s:
- marked as false by user
- generated automatically from other entries when guess is correct
Rather than iterating through entities, just get the number of the correct entity directly.
Then get one or two GPEs before and after.
"""
doc = prodigy_entry['text']
doc = nlp(doc)
geo_proced = geo.process_text(doc, require_maj=False)
# find the geoproced entity that matches the Prodigy entry
ent_text = np.asarray([gp['word'] for gp in geo_proced]) # get mask for correct ent
#print(ent_text)
match = ent_text == entry['meta']['word']
#print("match: ", match)
anti_match = np.abs(match - 1)
#print("Anti-match ", anti_match)
match_position = match.argmax()
geo_proc = geo_proced[match_position]
iso = geo.cts[prodigy_entry['label']] # convert country text label to ISO
feat = geo.features_to_matrix(geo_proc)
answer_x = feat['matrix']
label = np.asarray(feat['labels'])
if prodigy_entry['answer'] == "accept":
answer_binary = label == iso
answer_binary = answer_binary.astype('int')
#print(answer_x.shape)
#print(answer_binary.shape)
elif prodigy_entry['answer'] == "reject":
# all we know is that the label that was presented is wrong.
# just return the corresponding row in the feature matrix,
# and force the label to be 0
answer_binary = label == iso
answer_x = answer_x[answer_binary,:] # just take the row corresponding to the answer
answer_binary = np.asarray([0]) # set the outcome to 0 because reject
# NEED TO SHARE LABELS ACROSS! THE CORRECT ONE MIGHT NOT EVEN APPEAR FOR ALL ENTITIES
x = feat['matrix']
other_x = x[anti_match,:]
#print(other_x)
#print(label[anti_match])
# here, need to get the rows corresponding to the correct label
# print(geo_proc['meta'])
# here's where we get the other place name features.
# Need to:
# 1. do features_to_matrix but use the label of the current entity
# to determine 0/1 in the feature matrix
# 2. put them all into one big feature matrix,
# 3. ...ordering by distance? And need to decide max entity length
# 4. also include these distances as one of the features
#print(answer_x.shape[0])
#print(answer_binary.shape[0])
try:
if answer_x.shape[0] == answer_binary.shape[0]:
return (answer_x, answer_binary)
except:
pass
|
Refreshes the FindMyiPhoneService endpoint,
This ensures that the location data is up-to-date.
|
def refresh_client(self):
""" Refreshes the FindMyiPhoneService endpoint,
This ensures that the location data is up-to-date.
"""
req = self.session.post(
self._fmip_refresh_url,
params=self.params,
data=json.dumps(
{
'clientContext': {
'fmly': True,
'shouldLocate': True,
'selectedDevice': 'all',
}
}
)
)
self.response = req.json()
for device_info in self.response['content']:
device_id = device_info['id']
if device_id not in self._devices:
self._devices[device_id] = AppleDevice(
device_info,
self.session,
self.params,
manager=self,
sound_url=self._fmip_sound_url,
lost_url=self._fmip_lost_url,
message_url=self._fmip_message_url,
)
else:
self._devices[device_id].update(device_info)
if not self._devices:
raise PyiCloudNoDevicesException()
|
Returns status information for device.
This returns only a subset of possible properties.
|
def status(self, additional=[]):
""" Returns status information for device.
This returns only a subset of possible properties.
"""
self.manager.refresh_client()
fields = ['batteryLevel', 'deviceDisplayName', 'deviceStatus', 'name']
fields += additional
properties = {}
for field in fields:
properties[field] = self.content.get(field)
return properties
|
Send a request to the device to play a sound.
It's possible to pass a custom message by changing the `subject`.
|
def play_sound(self, subject='Find My iPhone Alert'):
""" Send a request to the device to play a sound.
It's possible to pass a custom message by changing the `subject`.
"""
data = json.dumps({
'device': self.content['id'],
'subject': subject,
'clientContext': {
'fmly': True
}
})
self.session.post(
self.sound_url,
params=self.params,
data=data
)
|
Send a request to the device to play a sound.
It's possible to pass a custom message by changing the `subject`.
|
def display_message(
self, subject='Find My iPhone Alert', message="This is a note",
sounds=False
):
""" Send a request to the device to play a sound.
It's possible to pass a custom message by changing the `subject`.
"""
data = json.dumps(
{
'device': self.content['id'],
'subject': subject,
'sound': sounds,
'userText': True,
'text': message
}
)
self.session.post(
self.message_url,
params=self.params,
data=data
)
|
Send a request to the device to trigger 'lost mode'.
The device will show the message in `text`, and if a number has
been passed, then the person holding the device can call
the number without entering the passcode.
|
def lost_device(
self, number,
text='This iPhone has been lost. Please call me.',
newpasscode=""
):
""" Send a request to the device to trigger 'lost mode'.
The device will show the message in `text`, and if a number has
been passed, then the person holding the device can call
the number without entering the passcode.
"""
data = json.dumps({
'text': text,
'userText': True,
'ownerNbr': number,
'lostModeEnabled': True,
'trackingEnabled': True,
'device': self.content['id'],
'passcode': newpasscode
})
self.session.post(
self.lost_url,
params=self.params,
data=data
)
|
Fetches a single event's details by specifying a pguid
(a calendar) and a guid (an event's ID).
|
def get_event_detail(self, pguid, guid):
"""
Fetches a single event's details by specifying a pguid
(a calendar) and a guid (an event's ID).
"""
params = dict(self.params)
params.update({'lang': 'en-us', 'usertz': get_localzone().zone})
url = '%s/%s/%s' % (self._calendar_event_detail_url, pguid, guid)
req = self.session.get(url, params=params)
self.response = req.json()
return self.response['Event'][0]
|
Retrieves events for a given date range, by default, this month.
|
def events(self, from_dt=None, to_dt=None):
"""
Retrieves events for a given date range, by default, this month.
"""
self.refresh_client(from_dt, to_dt)
return self.response['Event']
|
Retrieves calendars for this month
|
def calendars(self):
"""
Retrieves calendars for this month
"""
today = datetime.today()
first_day, last_day = monthrange(today.year, today.month)
from_dt = datetime(today.year, today.month, first_day)
to_dt = datetime(today.year, today.month, last_day)
params = dict(self.params)
params.update({
'lang': 'en-us',
'usertz': get_localzone().zone,
'startDate': from_dt.strftime('%Y-%m-%d'),
'endDate': to_dt.strftime('%Y-%m-%d')
})
req = self.session.get(self._calendars, params=params)
self.response = req.json()
return self.response['Collection']
|
This helper will output the idevice to a pickled file named
after the passed filename.
This allows the data to be used without resorting to screen / pipe
scrapping.
|
def create_pickled_data(idevice, filename):
"""This helper will output the idevice to a pickled file named
after the passed filename.
This allows the data to be used without resorting to screen / pipe
scrapping. """
data = {}
for x in idevice.content:
data[x] = idevice.content[x]
location = filename
pickle_file = open(location, 'wb')
pickle.dump(data, pickle_file, protocol=pickle.HIGHEST_PROTOCOL)
pickle_file.close()
|
Main commandline entrypoint
|
def main(args=None):
"""Main commandline entrypoint"""
if args is None:
args = sys.argv[1:]
parser = argparse.ArgumentParser(
description="Find My iPhone CommandLine Tool")
parser.add_argument(
"--username",
action="store",
dest="username",
default="",
help="Apple ID to Use"
)
parser.add_argument(
"--password",
action="store",
dest="password",
default="",
help=(
"Apple ID Password to Use; if unspecified, password will be "
"fetched from the system keyring."
)
)
parser.add_argument(
"-n",
"--non-interactive",
action="store_false",
dest="interactive",
default=True,
help="Disable interactive prompts."
)
parser.add_argument(
"--delete-from-keyring",
action="store_true",
dest="delete_from_keyring",
default=False,
help="Delete stored password in system keyring for this username.",
)
parser.add_argument(
"--list",
action="store_true",
dest="list",
default=False,
help="Short Listings for Device(s) associated with account",
)
parser.add_argument(
"--llist",
action="store_true",
dest="longlist",
default=False,
help="Detailed Listings for Device(s) associated with account",
)
parser.add_argument(
"--locate",
action="store_true",
dest="locate",
default=False,
help="Retrieve Location for the iDevice (non-exclusive).",
)
# Restrict actions to a specific devices UID / DID
parser.add_argument(
"--device",
action="store",
dest="device_id",
default=False,
help="Only effect this device",
)
# Trigger Sound Alert
parser.add_argument(
"--sound",
action="store_true",
dest="sound",
default=False,
help="Play a sound on the device",
)
# Trigger Message w/Sound Alert
parser.add_argument(
"--message",
action="store",
dest="message",
default=False,
help="Optional Text Message to display with a sound",
)
# Trigger Message (without Sound) Alert
parser.add_argument(
"--silentmessage",
action="store",
dest="silentmessage",
default=False,
help="Optional Text Message to display with no sounds",
)
# Lost Mode
parser.add_argument(
"--lostmode",
action="store_true",
dest="lostmode",
default=False,
help="Enable Lost mode for the device",
)
parser.add_argument(
"--lostphone",
action="store",
dest="lost_phone",
default=False,
help="Phone Number allowed to call when lost mode is enabled",
)
parser.add_argument(
"--lostpassword",
action="store",
dest="lost_password",
default=False,
help="Forcibly active this passcode on the idevice",
)
parser.add_argument(
"--lostmessage",
action="store",
dest="lost_message",
default="",
help="Forcibly display this message when activating lost mode.",
)
# Output device data to an pickle file
parser.add_argument(
"--outputfile",
action="store_true",
dest="output_to_file",
default="",
help="Save device data to a file in the current directory.",
)
command_line = parser.parse_args(args)
username = command_line.username
password = command_line.password
if username and command_line.delete_from_keyring:
utils.delete_password_in_keyring(username)
failure_count = 0
while True:
# Which password we use is determined by your username, so we
# do need to check for this first and separately.
if not username:
parser.error('No username supplied')
if not password:
password = utils.get_password(
username,
interactive=command_line.interactive
)
if not password:
parser.error('No password supplied')
try:
api = pyicloud.PyiCloudService(
username.strip(),
password.strip()
)
if (
not utils.password_exists_in_keyring(username) and
command_line.interactive and
confirm("Save password in keyring? ")
):
utils.store_password_in_keyring(username, password)
if api.requires_2sa:
import click
print("Two-step authentication required.",
"Your trusted devices are:")
devices = api.trusted_devices
for i, device in enumerate(devices):
print(" %s: %s" % (
i, device.get(
'deviceName',
"SMS to %s" % device.get('phoneNumber'))))
device = click.prompt('Which device would you like to use?',
default=0)
device = devices[device]
if not api.send_verification_code(device):
print("Failed to send verification code")
sys.exit(1)
code = click.prompt('Please enter validation code')
if not api.validate_verification_code(device, code):
print("Failed to verify verification code")
sys.exit(1)
break
except pyicloud.exceptions.PyiCloudFailedLoginException:
# If they have a stored password; we just used it and
# it did not work; let's delete it if there is one.
if utils.password_exists_in_keyring(username):
utils.delete_password_in_keyring(username)
message = "Bad username or password for {username}".format(
username=username,
)
password = None
failure_count += 1
if failure_count >= 3:
raise RuntimeError(message)
print(message, file=sys.stderr)
for dev in api.devices:
if (
not command_line.device_id or
(
command_line.device_id.strip().lower() ==
dev.content["id"].strip().lower()
)
):
# List device(s)
if command_line.locate:
dev.location()
if command_line.output_to_file:
create_pickled_data(
dev,
filename=(
dev.content["name"].strip().lower() + ".fmip_snapshot"
)
)
contents = dev.content
if command_line.longlist:
print("-"*30)
print(contents["name"])
for x in contents:
print("%20s - %s" % (x, contents[x]))
elif command_line.list:
print("-"*30)
print("Name - %s" % contents["name"])
print("Display Name - %s" % contents["deviceDisplayName"])
print("Location - %s" % contents["location"])
print("Battery Level - %s" % contents["batteryLevel"])
print("Battery Status- %s" % contents["batteryStatus"])
print("Device Class - %s" % contents["deviceClass"])
print("Device Model - %s" % contents["deviceModel"])
# Play a Sound on a device
if command_line.sound:
if command_line.device_id:
dev.play_sound()
else:
raise RuntimeError(
"\n\n\t\t%s %s\n\n" % (
"Sounds can only be played on a singular device.",
DEVICE_ERROR
)
)
# Display a Message on the device
if command_line.message:
if command_line.device_id:
dev.display_message(
subject='A Message',
message=command_line.message,
sounds=True
)
else:
raise RuntimeError(
"%s %s" % (
"Messages can only be played "
"on a singular device.",
DEVICE_ERROR
)
)
# Display a Silent Message on the device
if command_line.silentmessage:
if command_line.device_id:
dev.display_message(
subject='A Silent Message',
message=command_line.silentmessage,
sounds=False
)
else:
raise RuntimeError(
"%s %s" % (
"Silent Messages can only be played "
"on a singular device.",
DEVICE_ERROR
)
)
# Enable Lost mode
if command_line.lostmode:
if command_line.device_id:
dev.lost_device(
number=command_line.lost_phone.strip(),
text=command_line.lost_message.strip(),
newpasscode=command_line.lost_password.strip()
)
else:
raise RuntimeError(
"%s %s" % (
"Lost Mode can only be activated "
"on a singular device.",
DEVICE_ERROR
)
)
|
Refreshes the ContactsService endpoint, ensuring that the
contacts data is up-to-date.
|
def refresh_client(self, from_dt=None, to_dt=None):
"""
Refreshes the ContactsService endpoint, ensuring that the
contacts data is up-to-date.
"""
params_contacts = dict(self.params)
params_contacts.update({
'clientVersion': '2.1',
'locale': 'en_US',
'order': 'last,first',
})
req = self.session.get(
self._contacts_refresh_url,
params=params_contacts
)
self.response = req.json()
params_refresh = dict(self.params)
params_refresh.update({
'prefToken': req.json()["prefToken"],
'syncToken': req.json()["syncToken"],
})
self.session.post(self._contacts_changeset_url, params=params_refresh)
req = self.session.get(
self._contacts_refresh_url,
params=params_contacts
)
self.response = req.json()
|
Handles authentication, and persists the X-APPLE-WEB-KB cookie so that
subsequent logins will not cause additional e-mails from Apple.
|
def authenticate(self):
"""
Handles authentication, and persists the X-APPLE-WEB-KB cookie so that
subsequent logins will not cause additional e-mails from Apple.
"""
logger.info("Authenticating as %s", self.user['apple_id'])
data = dict(self.user)
# We authenticate every time, so "remember me" is not needed
data.update({'extended_login': False})
try:
req = self.session.post(
self._base_login_url,
params=self.params,
data=json.dumps(data)
)
except PyiCloudAPIResponseError as error:
msg = 'Invalid email/password combination.'
raise PyiCloudFailedLoginException(msg, error)
resp = req.json()
self.params.update({'dsid': resp['dsInfo']['dsid']})
if not os.path.exists(self._cookie_directory):
os.mkdir(self._cookie_directory)
self.session.cookies.save()
logger.debug("Cookies saved to %s", self._get_cookiejar_path())
self.data = resp
self.webservices = self.data['webservices']
logger.info("Authentication completed successfully")
logger.debug(self.params)
|
Returns devices trusted for two-step authentication.
|
def trusted_devices(self):
""" Returns devices trusted for two-step authentication."""
request = self.session.get(
'%s/listDevices' % self._setup_endpoint,
params=self.params
)
return request.json().get('devices')
|
Requests that a verification code is sent to the given device
|
def send_verification_code(self, device):
""" Requests that a verification code is sent to the given device"""
data = json.dumps(device)
request = self.session.post(
'%s/sendVerificationCode' % self._setup_endpoint,
params=self.params,
data=data
)
return request.json().get('success', False)
|
Verifies a verification code received on a trusted device
|
def validate_verification_code(self, device, code):
""" Verifies a verification code received on a trusted device"""
device.update({
'verificationCode': code,
'trustBrowser': True
})
data = json.dumps(device)
try:
request = self.session.post(
'%s/validateVerificationCode' % self._setup_endpoint,
params=self.params,
data=data
)
except PyiCloudAPIResponseError as error:
if error.code == -21669:
# Wrong verification code
return False
raise
# Re-authenticate, which will both update the HSA data, and
# ensure that we save the X-APPLE-WEBAUTH-HSA-TRUST cookie.
self.authenticate()
return not self.requires_2sa
|
Return all devices.
|
def devices(self):
""" Return all devices."""
service_root = self.webservices['findme']['url']
return FindMyiPhoneServiceManager(
service_root,
self.session,
self.params
)
|
Sends the request object using the specified pool. If a pool isn't
specified this method blocks. Pools are useful because you can specify size
and can hence limit concurrency.
|
def send(r, pool=None, stream=False):
"""Sends the request object using the specified pool. If a pool isn't
specified this method blocks. Pools are useful because you can specify size
and can hence limit concurrency."""
if pool is not None:
return pool.spawn(r.send, stream=stream)
return gevent.spawn(r.send, stream=stream)
|
Concurrently converts a list of Requests to Responses.
:param requests: a collection of Request objects.
:param stream: If True, the content will not be downloaded immediately.
:param size: Specifies the number of requests to make at a time. If None, no throttling occurs.
:param exception_handler: Callback function, called when exception occured. Params: Request, Exception
:param gtimeout: Gevent joinall timeout in seconds. (Note: unrelated to requests timeout)
|
def map(requests, stream=False, size=None, exception_handler=None, gtimeout=None):
"""Concurrently converts a list of Requests to Responses.
:param requests: a collection of Request objects.
:param stream: If True, the content will not be downloaded immediately.
:param size: Specifies the number of requests to make at a time. If None, no throttling occurs.
:param exception_handler: Callback function, called when exception occured. Params: Request, Exception
:param gtimeout: Gevent joinall timeout in seconds. (Note: unrelated to requests timeout)
"""
requests = list(requests)
pool = Pool(size) if size else None
jobs = [send(r, pool, stream=stream) for r in requests]
gevent.joinall(jobs, timeout=gtimeout)
ret = []
for request in requests:
if request.response is not None:
ret.append(request.response)
elif exception_handler and hasattr(request, 'exception'):
ret.append(exception_handler(request, request.exception))
else:
ret.append(None)
return ret
|
Concurrently converts a generator object of Requests to
a generator of Responses.
:param requests: a generator of Request objects.
:param stream: If True, the content will not be downloaded immediately.
:param size: Specifies the number of requests to make at a time. default is 2
:param exception_handler: Callback function, called when exception occured. Params: Request, Exception
|
def imap(requests, stream=False, size=2, exception_handler=None):
"""Concurrently converts a generator object of Requests to
a generator of Responses.
:param requests: a generator of Request objects.
:param stream: If True, the content will not be downloaded immediately.
:param size: Specifies the number of requests to make at a time. default is 2
:param exception_handler: Callback function, called when exception occured. Params: Request, Exception
"""
pool = Pool(size)
def send(r):
return r.send(stream=stream)
for request in pool.imap_unordered(send, requests):
if request.response is not None:
yield request.response
elif exception_handler:
ex_result = exception_handler(request, request.exception)
if ex_result is not None:
yield ex_result
pool.join()
|
Prepares request based on parameter passed to constructor and optional ``kwargs```.
Then sends request and saves response to :attr:`response`
:returns: ``Response``
|
def send(self, **kwargs):
"""
Prepares request based on parameter passed to constructor and optional ``kwargs```.
Then sends request and saves response to :attr:`response`
:returns: ``Response``
"""
merged_kwargs = {}
merged_kwargs.update(self.kwargs)
merged_kwargs.update(kwargs)
try:
self.response = self.session.request(self.method,
self.url, **merged_kwargs)
except Exception as e:
self.exception = e
self.traceback = traceback.format_exc()
return self
|
Set user profile within a room.
This sets displayname and avatar_url for the logged in user only in a
specific room. It does not change the user's global user profile.
|
def set_user_profile(self,
displayname=None,
avatar_url=None,
reason="Changing room profile information"):
"""Set user profile within a room.
This sets displayname and avatar_url for the logged in user only in a
specific room. It does not change the user's global user profile.
"""
member = self.client.api.get_membership(self.room_id, self.client.user_id)
if member["membership"] != "join":
raise Exception("Can't set profile if you have not joined the room.")
if displayname is None:
displayname = member["displayname"]
if avatar_url is None:
avatar_url = member["avatar_url"]
self.client.api.set_membership(
self.room_id,
self.client.user_id,
'join',
reason, {
"displayname": displayname,
"avatar_url": avatar_url
}
)
|
Calculates the display name for a room.
|
def display_name(self):
"""Calculates the display name for a room."""
if self.name:
return self.name
elif self.canonical_alias:
return self.canonical_alias
# Member display names without me
members = [u.get_display_name(self) for u in self.get_joined_members() if
self.client.user_id != u.user_id]
members.sort()
if len(members) == 1:
return members[0]
elif len(members) == 2:
return "{0} and {1}".format(members[0], members[1])
elif len(members) > 2:
return "{0} and {1} others".format(members[0], len(members) - 1)
else: # len(members) <= 0 or not an integer
# TODO i18n
return "Empty room"
|
Send a plain text message to the room.
|
def send_text(self, text):
"""Send a plain text message to the room."""
return self.client.api.send_message(self.room_id, text)
|
Send an html formatted message.
Args:
html (str): The html formatted message to be sent.
body (str): The unformatted body of the message to be sent.
|
def send_html(self, html, body=None, msgtype="m.text"):
"""Send an html formatted message.
Args:
html (str): The html formatted message to be sent.
body (str): The unformatted body of the message to be sent.
"""
return self.client.api.send_message_event(
self.room_id, "m.room.message", self.get_html_content(html, body, msgtype))
|
Send an emote (/me style) message to the room.
|
def send_emote(self, text):
"""Send an emote (/me style) message to the room."""
return self.client.api.send_emote(self.room_id, text)
|
Send a pre-uploaded file to the room.
See http://matrix.org/docs/spec/r0.2.0/client_server.html#m-file for
fileinfo.
Args:
url (str): The mxc url of the file.
name (str): The filename of the image.
fileinfo (): Extra information about the file
|
def send_file(self, url, name, **fileinfo):
"""Send a pre-uploaded file to the room.
See http://matrix.org/docs/spec/r0.2.0/client_server.html#m-file for
fileinfo.
Args:
url (str): The mxc url of the file.
name (str): The filename of the image.
fileinfo (): Extra information about the file
"""
return self.client.api.send_content(
self.room_id, url, name, "m.file",
extra_information=fileinfo
)
|
Send a notice (from bot) message to the room.
|
def send_notice(self, text):
"""Send a notice (from bot) message to the room."""
return self.client.api.send_notice(self.room_id, text)
|
Send a pre-uploaded image to the room.
See http://matrix.org/docs/spec/r0.0.1/client_server.html#m-image
for imageinfo
Args:
url (str): The mxc url of the image.
name (str): The filename of the image.
imageinfo (): Extra information about the image.
|
def send_image(self, url, name, **imageinfo):
"""Send a pre-uploaded image to the room.
See http://matrix.org/docs/spec/r0.0.1/client_server.html#m-image
for imageinfo
Args:
url (str): The mxc url of the image.
name (str): The filename of the image.
imageinfo (): Extra information about the image.
"""
return self.client.api.send_content(
self.room_id, url, name, "m.image",
extra_information=imageinfo
)
|
Send a location to the room.
See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-location
for thumb_info
Args:
geo_uri (str): The geo uri representing the location.
name (str): Description for the location.
thumb_url (str): URL to the thumbnail of the location.
thumb_info (): Metadata about the thumbnail, type ImageInfo.
|
def send_location(self, geo_uri, name, thumb_url=None, **thumb_info):
"""Send a location to the room.
See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-location
for thumb_info
Args:
geo_uri (str): The geo uri representing the location.
name (str): Description for the location.
thumb_url (str): URL to the thumbnail of the location.
thumb_info (): Metadata about the thumbnail, type ImageInfo.
"""
return self.client.api.send_location(self.room_id, geo_uri, name,
thumb_url, thumb_info)
|
Send a pre-uploaded video to the room.
See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-video
for videoinfo
Args:
url (str): The mxc url of the video.
name (str): The filename of the video.
videoinfo (): Extra information about the video.
|
def send_video(self, url, name, **videoinfo):
"""Send a pre-uploaded video to the room.
See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-video
for videoinfo
Args:
url (str): The mxc url of the video.
name (str): The filename of the video.
videoinfo (): Extra information about the video.
"""
return self.client.api.send_content(self.room_id, url, name, "m.video",
extra_information=videoinfo)
|
Send a pre-uploaded audio to the room.
See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-audio
for audioinfo
Args:
url (str): The mxc url of the audio.
name (str): The filename of the audio.
audioinfo (): Extra information about the audio.
|
def send_audio(self, url, name, **audioinfo):
"""Send a pre-uploaded audio to the room.
See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-audio
for audioinfo
Args:
url (str): The mxc url of the audio.
name (str): The filename of the audio.
audioinfo (): Extra information about the audio.
"""
return self.client.api.send_content(self.room_id, url, name, "m.audio",
extra_information=audioinfo)
|
Redacts the message with specified event_id for the given reason.
See https://matrix.org/docs/spec/r0.0.1/client_server.html#id112
|
def redact_message(self, event_id, reason=None):
"""Redacts the message with specified event_id for the given reason.
See https://matrix.org/docs/spec/r0.0.1/client_server.html#id112
"""
return self.client.api.redact_event(self.room_id, event_id, reason)
|
Add a callback handler for events going to this room.
Args:
callback (func(room, event)): Callback called when an event arrives.
event_type (str): The event_type to filter for.
Returns:
uuid.UUID: Unique id of the listener, can be used to identify the listener.
|
def add_listener(self, callback, event_type=None):
"""Add a callback handler for events going to this room.
Args:
callback (func(room, event)): Callback called when an event arrives.
event_type (str): The event_type to filter for.
Returns:
uuid.UUID: Unique id of the listener, can be used to identify the listener.
"""
listener_id = uuid4()
self.listeners.append(
{
'uid': listener_id,
'callback': callback,
'event_type': event_type
}
)
return listener_id
|
Remove listener with given uid.
|
def remove_listener(self, uid):
"""Remove listener with given uid."""
self.listeners[:] = (listener for listener in self.listeners
if listener['uid'] != uid)
|
Add a callback handler for ephemeral events going to this room.
Args:
callback (func(room, event)): Callback called when an ephemeral event arrives.
event_type (str): The event_type to filter for.
Returns:
uuid.UUID: Unique id of the listener, can be used to identify the listener.
|
def add_ephemeral_listener(self, callback, event_type=None):
"""Add a callback handler for ephemeral events going to this room.
Args:
callback (func(room, event)): Callback called when an ephemeral event arrives.
event_type (str): The event_type to filter for.
Returns:
uuid.UUID: Unique id of the listener, can be used to identify the listener.
"""
listener_id = uuid4()
self.ephemeral_listeners.append(
{
'uid': listener_id,
'callback': callback,
'event_type': event_type
}
)
return listener_id
|
Remove ephemeral listener with given uid.
|
def remove_ephemeral_listener(self, uid):
"""Remove ephemeral listener with given uid."""
self.ephemeral_listeners[:] = (listener for listener in self.ephemeral_listeners
if listener['uid'] != uid)
|
Invite a user to this room.
Returns:
boolean: Whether invitation was sent.
|
def invite_user(self, user_id):
"""Invite a user to this room.
Returns:
boolean: Whether invitation was sent.
"""
try:
self.client.api.invite_user(self.room_id, user_id)
return True
except MatrixRequestError:
return False
|
Kick a user from this room.
Args:
user_id (str): The matrix user id of a user.
reason (str): A reason for kicking the user.
Returns:
boolean: Whether user was kicked.
|
def kick_user(self, user_id, reason=""):
"""Kick a user from this room.
Args:
user_id (str): The matrix user id of a user.
reason (str): A reason for kicking the user.
Returns:
boolean: Whether user was kicked.
"""
try:
self.client.api.kick_user(self.room_id, user_id)
return True
except MatrixRequestError:
return False
|
Leave the room.
Returns:
boolean: Leaving the room was successful.
|
def leave(self):
"""Leave the room.
Returns:
boolean: Leaving the room was successful.
"""
try:
self.client.api.leave_room(self.room_id)
del self.client.rooms[self.room_id]
return True
except MatrixRequestError:
return False
|
Updates self.name and returns True if room name has changed.
|
def update_room_name(self):
"""Updates self.name and returns True if room name has changed."""
try:
response = self.client.api.get_room_name(self.room_id)
if "name" in response and response["name"] != self.name:
self.name = response["name"]
return True
else:
return False
except MatrixRequestError:
return False
|
Return True if room name successfully changed.
|
def set_room_name(self, name):
"""Return True if room name successfully changed."""
try:
self.client.api.set_room_name(self.room_id, name)
self.name = name
return True
except MatrixRequestError:
return False
|
Send a state event to the room.
Args:
event_type (str): The type of event that you are sending.
content (): An object with the content of the message.
state_key (str, optional): A unique key to identify the state.
|
def send_state_event(self, event_type, content, state_key=""):
"""Send a state event to the room.
Args:
event_type (str): The type of event that you are sending.
content (): An object with the content of the message.
state_key (str, optional): A unique key to identify the state.
"""
return self.client.api.send_state_event(
self.room_id,
event_type,
content,
state_key
)
|
Updates self.topic and returns True if room topic has changed.
|
def update_room_topic(self):
"""Updates self.topic and returns True if room topic has changed."""
try:
response = self.client.api.get_room_topic(self.room_id)
if "topic" in response and response["topic"] != self.topic:
self.topic = response["topic"]
return True
else:
return False
except MatrixRequestError:
return False
|
Set room topic.
Returns:
boolean: True if the topic changed, False if not
|
def set_room_topic(self, topic):
"""Set room topic.
Returns:
boolean: True if the topic changed, False if not
"""
try:
self.client.api.set_room_topic(self.room_id, topic)
self.topic = topic
return True
except MatrixRequestError:
return False
|
Get aliases information from room state.
Returns:
boolean: True if the aliases changed, False if not
|
def update_aliases(self):
"""Get aliases information from room state.
Returns:
boolean: True if the aliases changed, False if not
"""
try:
response = self.client.api.get_room_state(self.room_id)
for chunk in response:
if "content" in chunk and "aliases" in chunk["content"]:
if chunk["content"]["aliases"] != self.aliases:
self.aliases = chunk["content"]["aliases"]
return True
else:
return False
except MatrixRequestError:
return False
|
Add an alias to the room and return True if successful.
|
def add_room_alias(self, room_alias):
"""Add an alias to the room and return True if successful."""
try:
self.client.api.set_room_alias(self.room_id, room_alias)
return True
except MatrixRequestError:
return False
|
Returns list of joined members (User objects).
|
def get_joined_members(self):
"""Returns list of joined members (User objects)."""
if self._members:
return list(self._members.values())
response = self.client.api.get_room_members(self.room_id)
for event in response["chunk"]:
if event["content"]["membership"] == "join":
user_id = event["state_key"]
self._add_member(user_id, event["content"].get("displayname"))
return list(self._members.values())
|
Backfill handling of previous messages.
Args:
reverse (bool): When false messages will be backfilled in their original
order (old to new), otherwise the order will be reversed (new to old).
limit (int): Number of messages to go back.
|
def backfill_previous_messages(self, reverse=False, limit=10):
"""Backfill handling of previous messages.
Args:
reverse (bool): When false messages will be backfilled in their original
order (old to new), otherwise the order will be reversed (new to old).
limit (int): Number of messages to go back.
"""
res = self.client.api.get_room_messages(self.room_id, self.prev_batch,
direction="b", limit=limit)
events = res["chunk"]
if not reverse:
events = reversed(events)
for event in events:
self._put_event(event)
|
Modify the power level for a subset of users
Args:
users(dict): Power levels to assign to specific users, in the form
{"@name0:host0": 10, "@name1:host1": 100, "@name3:host3", None}
A level of None causes the user to revert to the default level
as specified by users_default.
users_default(int): Default power level for users in the room
Returns:
True if successful, False if not
|
def modify_user_power_levels(self, users=None, users_default=None):
"""Modify the power level for a subset of users
Args:
users(dict): Power levels to assign to specific users, in the form
{"@name0:host0": 10, "@name1:host1": 100, "@name3:host3", None}
A level of None causes the user to revert to the default level
as specified by users_default.
users_default(int): Default power level for users in the room
Returns:
True if successful, False if not
"""
try:
content = self.client.api.get_power_levels(self.room_id)
if users_default:
content["users_default"] = users_default
if users:
if "users" in content:
content["users"].update(users)
else:
content["users"] = users
# Remove any keys with value None
for user, power_level in list(content["users"].items()):
if power_level is None:
del content["users"][user]
self.client.api.set_power_levels(self.room_id, content)
return True
except MatrixRequestError:
return False
|
Modifies room power level requirements.
Args:
events(dict): Power levels required for sending specific event types,
in the form {"m.room.whatever0": 60, "m.room.whatever2": None}.
Overrides events_default and state_default for the specified
events. A level of None causes the target event to revert to the
default level as specified by events_default or state_default.
**kwargs: Key/value pairs specifying the power levels required for
various actions:
- events_default(int): Default level for sending message events
- state_default(int): Default level for sending state events
- invite(int): Inviting a user
- redact(int): Redacting an event
- ban(int): Banning a user
- kick(int): Kicking a user
Returns:
True if successful, False if not
|
def modify_required_power_levels(self, events=None, **kwargs):
"""Modifies room power level requirements.
Args:
events(dict): Power levels required for sending specific event types,
in the form {"m.room.whatever0": 60, "m.room.whatever2": None}.
Overrides events_default and state_default for the specified
events. A level of None causes the target event to revert to the
default level as specified by events_default or state_default.
**kwargs: Key/value pairs specifying the power levels required for
various actions:
- events_default(int): Default level for sending message events
- state_default(int): Default level for sending state events
- invite(int): Inviting a user
- redact(int): Redacting an event
- ban(int): Banning a user
- kick(int): Kicking a user
Returns:
True if successful, False if not
"""
try:
content = self.client.api.get_power_levels(self.room_id)
content.update(kwargs)
for key, value in list(content.items()):
if value is None:
del content[key]
if events:
if "events" in content:
content["events"].update(events)
else:
content["events"] = events
# Remove any keys with value None
for event, power_level in list(content["events"].items()):
if power_level is None:
del content["events"][event]
self.client.api.set_power_levels(self.room_id, content)
return True
except MatrixRequestError:
return False
|
Set how the room can be joined.
Args:
invite_only(bool): If True, users will have to be invited to join
the room. If False, anyone who knows the room link can join.
Returns:
True if successful, False if not
|
def set_invite_only(self, invite_only):
"""Set how the room can be joined.
Args:
invite_only(bool): If True, users will have to be invited to join
the room. If False, anyone who knows the room link can join.
Returns:
True if successful, False if not
"""
join_rule = "invite" if invite_only else "public"
try:
self.client.api.set_join_rule(self.room_id, join_rule)
self.invite_only = invite_only
return True
except MatrixRequestError:
return False
|
Set whether guests can join the room and return True if successful.
|
def set_guest_access(self, allow_guests):
"""Set whether guests can join the room and return True if successful."""
guest_access = "can_join" if allow_guests else "forbidden"
try:
self.client.api.set_guest_access(self.room_id, guest_access)
self.guest_access = allow_guests
return True
except MatrixRequestError:
return False
|
Enables encryption in the room.
NOTE: Once enabled, encryption cannot be disabled.
Returns:
True if successful, False if not
|
def enable_encryption(self):
"""Enables encryption in the room.
NOTE: Once enabled, encryption cannot be disabled.
Returns:
True if successful, False if not
"""
try:
self.send_state_event("m.room.encryption",
{"algorithm": "m.megolm.v1.aes-sha2"})
self.encrypted = True
return True
except MatrixRequestError:
return False
|
run the example.
|
def example(host, user, password, token):
"""run the example."""
client = None
try:
if token:
print('token login')
client = MatrixClient(host, token=token, user_id=user)
else:
print('password login')
client = MatrixClient(host)
token = client.login_with_password(user, password)
print('got token: %s' % token)
except MatrixRequestError as e:
print(e)
if e.code == 403:
print("Bad username or password")
exit(2)
elif e.code == 401:
print("Bad username or token")
exit(3)
else:
print("Verify server details.")
exit(4)
except MissingSchema as e:
print(e)
print("Bad formatting of URL.")
exit(5)
except InvalidSchema as e:
print(e)
print("Invalid URL schema")
exit(6)
print("is in rooms")
for room_id, room in client.get_rooms().items():
print(room_id)
|
Main entry.
|
def main():
"""Main entry."""
parser = argparse.ArgumentParser()
parser.add_argument("--host", type=str, required=True)
parser.add_argument("--user", type=str, required=True)
parser.add_argument("--password", type=str)
parser.add_argument("--token", type=str)
args = parser.parse_args()
if not args.password and not args.token:
print('password or token is required')
exit(1)
example(args.host, args.user, args.password, args.token)
|
.. warning::
Deprecated. Use sync instead.
Perform /initialSync.
Args:
limit (int): The limit= param to provide.
|
def initial_sync(self, limit=1):
"""
.. warning::
Deprecated. Use sync instead.
Perform /initialSync.
Args:
limit (int): The limit= param to provide.
"""
warnings.warn("initial_sync is deprecated. Use sync instead.", DeprecationWarning)
return self._send("GET", "/initialSync", query_params={"limit": limit})
|
Perform a sync request.
Args:
since (str): Optional. A token which specifies where to continue a sync from.
timeout_ms (int): Optional. The time in milliseconds to wait.
filter (int|str): Either a Filter ID or a JSON string.
full_state (bool): Return the full state for every room the user has joined
Defaults to false.
set_presence (str): Should the client be marked as "online" or" offline"
|
def sync(self, since=None, timeout_ms=30000, filter=None,
full_state=None, set_presence=None):
""" Perform a sync request.
Args:
since (str): Optional. A token which specifies where to continue a sync from.
timeout_ms (int): Optional. The time in milliseconds to wait.
filter (int|str): Either a Filter ID or a JSON string.
full_state (bool): Return the full state for every room the user has joined
Defaults to false.
set_presence (str): Should the client be marked as "online" or" offline"
"""
request = {
# non-integer timeouts appear to cause issues
"timeout": int(timeout_ms)
}
if since:
request["since"] = since
if filter:
request["filter"] = filter
if full_state:
request["full_state"] = json.dumps(full_state)
if set_presence:
request["set_presence"] = set_presence
return self._send("GET", "/sync", query_params=request,
api_path=MATRIX_V2_API_PATH)
|
Performs /register.
Args:
auth_body (dict): Authentication Params.
kind (str): Specify kind of account to register. Can be 'guest' or 'user'.
bind_email (bool): Whether to use email in registration and authentication.
username (str): The localpart of a Matrix ID.
password (str): The desired password of the account.
device_id (str): ID of the client device.
initial_device_display_name (str): Display name to be assigned.
inhibit_login (bool): Whether to login after registration. Defaults to false.
|
def register(self, auth_body=None, kind="user", bind_email=None,
username=None, password=None, device_id=None,
initial_device_display_name=None, inhibit_login=None):
"""Performs /register.
Args:
auth_body (dict): Authentication Params.
kind (str): Specify kind of account to register. Can be 'guest' or 'user'.
bind_email (bool): Whether to use email in registration and authentication.
username (str): The localpart of a Matrix ID.
password (str): The desired password of the account.
device_id (str): ID of the client device.
initial_device_display_name (str): Display name to be assigned.
inhibit_login (bool): Whether to login after registration. Defaults to false.
"""
content = {}
content["kind"] = kind
if auth_body:
content["auth"] = auth_body
if username:
content["username"] = username
if password:
content["password"] = password
if device_id:
content["device_id"] = device_id
if initial_device_display_name:
content["initial_device_display_name"] = \
initial_device_display_name
if bind_email:
content["bind_email"] = bind_email
if inhibit_login:
content["inhibit_login"] = inhibit_login
return self._send(
"POST",
"/register",
content=content,
query_params={'kind': kind}
)
|
Perform /login.
Args:
login_type (str): The value for the 'type' key.
**kwargs: Additional key/values to add to the JSON submitted.
|
def login(self, login_type, **kwargs):
"""Perform /login.
Args:
login_type (str): The value for the 'type' key.
**kwargs: Additional key/values to add to the JSON submitted.
"""
content = {
"type": login_type
}
for key in kwargs:
if kwargs[key]:
content[key] = kwargs[key]
return self._send("POST", "/login", content)
|
Perform /createRoom.
Args:
alias (str): Optional. The room alias name to set for this room.
name (str): Optional. Name for new room.
is_public (bool): Optional. The public/private visibility.
invitees (list<str>): Optional. The list of user IDs to invite.
federate (bool): Optional. Сan a room be federated.
Default to True.
|
def create_room(
self,
alias=None,
name=None,
is_public=False,
invitees=None,
federate=None
):
"""Perform /createRoom.
Args:
alias (str): Optional. The room alias name to set for this room.
name (str): Optional. Name for new room.
is_public (bool): Optional. The public/private visibility.
invitees (list<str>): Optional. The list of user IDs to invite.
federate (bool): Optional. Сan a room be federated.
Default to True.
"""
content = {
"visibility": "public" if is_public else "private"
}
if alias:
content["room_alias_name"] = alias
if invitees:
content["invite"] = invitees
if name:
content["name"] = name
if federate is not None:
content["creation_content"] = {'m.federate': federate}
return self._send("POST", "/createRoom", content)
|
Performs /join/$room_id
Args:
room_id_or_alias (str): The room ID or room alias to join.
|
def join_room(self, room_id_or_alias):
"""Performs /join/$room_id
Args:
room_id_or_alias (str): The room ID or room alias to join.
"""
if not room_id_or_alias:
raise MatrixError("No alias or room ID to join.")
path = "/join/%s" % quote(room_id_or_alias)
return self._send("POST", path)
|
Perform PUT /rooms/$room_id/state/$event_type
Args:
room_id(str): The room ID to send the state event in.
event_type(str): The state event type to send.
content(dict): The JSON content to send.
state_key(str): Optional. The state key for the event.
timestamp (int): Set origin_server_ts (For application services only)
|
def send_state_event(self, room_id, event_type, content, state_key="",
timestamp=None):
"""Perform PUT /rooms/$room_id/state/$event_type
Args:
room_id(str): The room ID to send the state event in.
event_type(str): The state event type to send.
content(dict): The JSON content to send.
state_key(str): Optional. The state key for the event.
timestamp (int): Set origin_server_ts (For application services only)
"""
path = "/rooms/%s/state/%s" % (
quote(room_id), quote(event_type),
)
if state_key:
path += "/%s" % (quote(state_key))
params = {}
if timestamp:
params["ts"] = timestamp
return self._send("PUT", path, content, query_params=params)
|
Deprecated. Use sync instead.
Performs /events
Args:
from_token (str): The 'from' query parameter.
timeout (int): Optional. The 'timeout' query parameter.
|
def event_stream(self, from_token, timeout=30000):
""" Deprecated. Use sync instead.
Performs /events
Args:
from_token (str): The 'from' query parameter.
timeout (int): Optional. The 'timeout' query parameter.
"""
warnings.warn("event_stream is deprecated. Use sync instead.",
DeprecationWarning)
path = "/events"
return self._send(
"GET", path, query_params={
"timeout": timeout,
"from": from_token
}
)
|
Perform GET /rooms/$room_id/state/$event_type
Args:
room_id(str): The room ID.
event_type (str): The type of the event.
Raises:
MatrixRequestError(code=404) if the state event is not found.
|
def get_state_event(self, room_id, event_type):
"""Perform GET /rooms/$room_id/state/$event_type
Args:
room_id(str): The room ID.
event_type (str): The type of the event.
Raises:
MatrixRequestError(code=404) if the state event is not found.
"""
return self._send("GET", "/rooms/{}/state/{}".format(quote(room_id), event_type))
|
Perform PUT /rooms/$room_id/send/$event_type
Args:
room_id (str): The room ID to send the message event in.
event_type (str): The event type to send.
content (dict): The JSON content to send.
txn_id (int): Optional. The transaction ID to use.
timestamp (int): Set origin_server_ts (For application services only)
|
def send_message_event(self, room_id, event_type, content, txn_id=None,
timestamp=None):
"""Perform PUT /rooms/$room_id/send/$event_type
Args:
room_id (str): The room ID to send the message event in.
event_type (str): The event type to send.
content (dict): The JSON content to send.
txn_id (int): Optional. The transaction ID to use.
timestamp (int): Set origin_server_ts (For application services only)
"""
if not txn_id:
txn_id = self._make_txn_id()
path = "/rooms/%s/send/%s/%s" % (
quote(room_id), quote(event_type), quote(str(txn_id)),
)
params = {}
if timestamp:
params["ts"] = timestamp
return self._send("PUT", path, content, query_params=params)
|
Perform PUT /rooms/$room_id/redact/$event_id/$txn_id/
Args:
room_id(str): The room ID to redact the message event in.
event_id(str): The event id to redact.
reason (str): Optional. The reason the message was redacted.
txn_id(int): Optional. The transaction ID to use.
timestamp(int): Optional. Set origin_server_ts (For application services only)
|
def redact_event(self, room_id, event_id, reason=None, txn_id=None, timestamp=None):
"""Perform PUT /rooms/$room_id/redact/$event_id/$txn_id/
Args:
room_id(str): The room ID to redact the message event in.
event_id(str): The event id to redact.
reason (str): Optional. The reason the message was redacted.
txn_id(int): Optional. The transaction ID to use.
timestamp(int): Optional. Set origin_server_ts (For application services only)
"""
if not txn_id:
txn_id = self._make_txn_id()
path = '/rooms/%s/redact/%s/%s' % (
room_id, event_id, txn_id
)
content = {}
if reason:
content['reason'] = reason
params = {}
if timestamp:
params["ts"] = timestamp
return self._send("PUT", path, content, query_params=params)
|
Send m.location message event
Args:
room_id (str): The room ID to send the event in.
geo_uri (str): The geo uri representing the location.
name (str): Description for the location.
thumb_url (str): URL to the thumbnail of the location.
thumb_info (dict): Metadata about the thumbnail, type ImageInfo.
timestamp (int): Set origin_server_ts (For application services only)
|
def send_location(self, room_id, geo_uri, name, thumb_url=None, thumb_info=None,
timestamp=None):
"""Send m.location message event
Args:
room_id (str): The room ID to send the event in.
geo_uri (str): The geo uri representing the location.
name (str): Description for the location.
thumb_url (str): URL to the thumbnail of the location.
thumb_info (dict): Metadata about the thumbnail, type ImageInfo.
timestamp (int): Set origin_server_ts (For application services only)
"""
content_pack = {
"geo_uri": geo_uri,
"msgtype": "m.location",
"body": name,
}
if thumb_url:
content_pack["thumbnail_url"] = thumb_url
if thumb_info:
content_pack["thumbnail_info"] = thumb_info
return self.send_message_event(room_id, "m.room.message", content_pack,
timestamp=timestamp)
|
Perform PUT /rooms/$room_id/send/m.room.message
Args:
room_id (str): The room ID to send the event in.
text_content (str): The m.text body to send.
timestamp (int): Set origin_server_ts (For application services only)
|
def send_message(self, room_id, text_content, msgtype="m.text", timestamp=None):
"""Perform PUT /rooms/$room_id/send/m.room.message
Args:
room_id (str): The room ID to send the event in.
text_content (str): The m.text body to send.
timestamp (int): Set origin_server_ts (For application services only)
"""
return self.send_message_event(
room_id, "m.room.message",
self.get_text_body(text_content, msgtype),
timestamp=timestamp
)
|
Perform PUT /rooms/$room_id/send/m.room.message with m.emote msgtype
Args:
room_id (str): The room ID to send the event in.
text_content (str): The m.emote body to send.
timestamp (int): Set origin_server_ts (For application services only)
|
def send_emote(self, room_id, text_content, timestamp=None):
"""Perform PUT /rooms/$room_id/send/m.room.message with m.emote msgtype
Args:
room_id (str): The room ID to send the event in.
text_content (str): The m.emote body to send.
timestamp (int): Set origin_server_ts (For application services only)
"""
return self.send_message_event(
room_id, "m.room.message",
self.get_emote_body(text_content),
timestamp=timestamp
)
|
Perform PUT /rooms/$room_id/send/m.room.message with m.notice msgtype
Args:
room_id (str): The room ID to send the event in.
text_content (str): The m.notice body to send.
timestamp (int): Set origin_server_ts (For application services only)
|
def send_notice(self, room_id, text_content, timestamp=None):
"""Perform PUT /rooms/$room_id/send/m.room.message with m.notice msgtype
Args:
room_id (str): The room ID to send the event in.
text_content (str): The m.notice body to send.
timestamp (int): Set origin_server_ts (For application services only)
"""
body = {
"msgtype": "m.notice",
"body": text_content
}
return self.send_message_event(room_id, "m.room.message", body,
timestamp=timestamp)
|
Perform GET /rooms/{roomId}/messages.
Args:
room_id (str): The room's id.
token (str): The token to start returning events from.
direction (str): The direction to return events from. One of: ["b", "f"].
limit (int): The maximum number of events to return.
to (str): The token to stop returning events at.
|
def get_room_messages(self, room_id, token, direction, limit=10, to=None):
"""Perform GET /rooms/{roomId}/messages.
Args:
room_id (str): The room's id.
token (str): The token to start returning events from.
direction (str): The direction to return events from. One of: ["b", "f"].
limit (int): The maximum number of events to return.
to (str): The token to stop returning events at.
"""
query = {
"roomId": room_id,
"from": token,
"dir": direction,
"limit": limit,
}
if to:
query["to"] = to
return self._send("GET", "/rooms/{}/messages".format(quote(room_id)),
query_params=query, api_path="/_matrix/client/r0")
|
Perform PUT /rooms/$room_id/state/m.room.name
Args:
room_id (str): The room ID
name (str): The new room name
timestamp (int): Set origin_server_ts (For application services only)
|
def set_room_name(self, room_id, name, timestamp=None):
"""Perform PUT /rooms/$room_id/state/m.room.name
Args:
room_id (str): The room ID
name (str): The new room name
timestamp (int): Set origin_server_ts (For application services only)
"""
body = {
"name": name
}
return self.send_state_event(room_id, "m.room.name", body, timestamp=timestamp)
|
Perform PUT /rooms/$room_id/state/m.room.topic
Args:
room_id (str): The room ID
topic (str): The new room topic
timestamp (int): Set origin_server_ts (For application services only)
|
def set_room_topic(self, room_id, topic, timestamp=None):
"""Perform PUT /rooms/$room_id/state/m.room.topic
Args:
room_id (str): The room ID
topic (str): The new room topic
timestamp (int): Set origin_server_ts (For application services only)
"""
body = {
"topic": topic
}
return self.send_state_event(room_id, "m.room.topic", body, timestamp=timestamp)
|
Perform PUT /rooms/$room_id/state/m.room.power_levels
Note that any power levels which are not explicitly specified
in the content arg are reset to default values.
Args:
room_id (str): The room ID
content (dict): The JSON content to send. See example content below.
Example::
api = MatrixHttpApi("http://example.com", token="foobar")
api.set_power_levels("!exampleroom:example.com",
{
"ban": 50, # defaults to 50 if unspecified
"events": {
"m.room.name": 100, # must have PL 100 to change room name
"m.room.power_levels": 100 # must have PL 100 to change PLs
},
"events_default": 0, # defaults to 0
"invite": 50, # defaults to 50
"kick": 50, # defaults to 50
"redact": 50, # defaults to 50
"state_default": 50, # defaults to 50 if m.room.power_levels exists
"users": {
"@someguy:example.com": 100 # defaults to 0
},
"users_default": 0 # defaults to 0
}
)
|
def set_power_levels(self, room_id, content):
"""Perform PUT /rooms/$room_id/state/m.room.power_levels
Note that any power levels which are not explicitly specified
in the content arg are reset to default values.
Args:
room_id (str): The room ID
content (dict): The JSON content to send. See example content below.
Example::
api = MatrixHttpApi("http://example.com", token="foobar")
api.set_power_levels("!exampleroom:example.com",
{
"ban": 50, # defaults to 50 if unspecified
"events": {
"m.room.name": 100, # must have PL 100 to change room name
"m.room.power_levels": 100 # must have PL 100 to change PLs
},
"events_default": 0, # defaults to 0
"invite": 50, # defaults to 50
"kick": 50, # defaults to 50
"redact": 50, # defaults to 50
"state_default": 50, # defaults to 50 if m.room.power_levels exists
"users": {
"@someguy:example.com": 100 # defaults to 0
},
"users_default": 0 # defaults to 0
}
)
"""
# Synapse returns M_UNKNOWN if body['events'] is omitted,
# as of 2016-10-31
if "events" not in content:
content["events"] = {}
return self.send_state_event(room_id, "m.room.power_levels", content)
|
Perform POST /rooms/$room_id/invite
Args:
room_id (str): The room ID
user_id (str): The user ID of the invitee
|
def invite_user(self, room_id, user_id):
"""Perform POST /rooms/$room_id/invite
Args:
room_id (str): The room ID
user_id (str): The user ID of the invitee
"""
body = {
"user_id": user_id
}
return self._send("POST", "/rooms/" + room_id + "/invite", body)
|
Calls set_membership with membership="leave" for the user_id provided
|
def kick_user(self, room_id, user_id, reason=""):
"""Calls set_membership with membership="leave" for the user_id provided
"""
self.set_membership(room_id, user_id, "leave", reason)
|
Perform PUT /rooms/$room_id/state/m.room.member/$user_id
Args:
room_id (str): The room ID
user_id (str): The user ID
membership (str): New membership value
reason (str): The reason
timestamp (int): Set origin_server_ts (For application services only)
|
def set_membership(self, room_id, user_id, membership, reason="", profile=None,
timestamp=None):
"""Perform PUT /rooms/$room_id/state/m.room.member/$user_id
Args:
room_id (str): The room ID
user_id (str): The user ID
membership (str): New membership value
reason (str): The reason
timestamp (int): Set origin_server_ts (For application services only)
"""
if profile is None:
profile = {}
body = {
"membership": membership,
"reason": reason
}
if 'displayname' in profile:
body["displayname"] = profile["displayname"]
if 'avatar_url' in profile:
body["avatar_url"] = profile["avatar_url"]
return self.send_state_event(room_id, "m.room.member", body, state_key=user_id,
timestamp=timestamp)
|
Perform POST /rooms/$room_id/ban
Args:
room_id (str): The room ID
user_id (str): The user ID of the banee(sic)
reason (str): The reason for this ban
|
def ban_user(self, room_id, user_id, reason=""):
"""Perform POST /rooms/$room_id/ban
Args:
room_id (str): The room ID
user_id (str): The user ID of the banee(sic)
reason (str): The reason for this ban
"""
body = {
"user_id": user_id,
"reason": reason
}
return self._send("POST", "/rooms/" + room_id + "/ban", body)
|
Download raw media from provided mxc URL.
Args:
mxcurl (str): mxc media URL.
allow_remote (bool): indicates to the server that it should not
attempt to fetch the media if it is deemed remote. Defaults
to true if not provided.
|
def media_download(self, mxcurl, allow_remote=True):
"""Download raw media from provided mxc URL.
Args:
mxcurl (str): mxc media URL.
allow_remote (bool): indicates to the server that it should not
attempt to fetch the media if it is deemed remote. Defaults
to true if not provided.
"""
query_params = {}
if not allow_remote:
query_params["allow_remote"] = False
if mxcurl.startswith('mxc://'):
return self._send(
"GET", mxcurl[6:],
api_path="/_matrix/media/r0/download/",
query_params=query_params,
return_json=False
)
else:
raise ValueError(
"MXC URL '%s' did not begin with 'mxc://'" % mxcurl
)
|
Perform POST /rooms/$room_id/unban
Args:
room_id (str): The room ID
user_id (str): The user ID of the banee(sic)
|
def unban_user(self, room_id, user_id):
"""Perform POST /rooms/$room_id/unban
Args:
room_id (str): The room ID
user_id (str): The user ID of the banee(sic)
"""
body = {
"user_id": user_id
}
return self._send("POST", "/rooms/" + room_id + "/unban", body)
|
Download raw media thumbnail from provided mxc URL.
Args:
mxcurl (str): mxc media URL
width (int): desired thumbnail width
height (int): desired thumbnail height
method (str): thumb creation method. Must be
in ['scale', 'crop']. Default 'scale'.
allow_remote (bool): indicates to the server that it should not
attempt to fetch the media if it is deemed remote. Defaults
to true if not provided.
|
def get_thumbnail(self, mxcurl, width, height, method='scale', allow_remote=True):
"""Download raw media thumbnail from provided mxc URL.
Args:
mxcurl (str): mxc media URL
width (int): desired thumbnail width
height (int): desired thumbnail height
method (str): thumb creation method. Must be
in ['scale', 'crop']. Default 'scale'.
allow_remote (bool): indicates to the server that it should not
attempt to fetch the media if it is deemed remote. Defaults
to true if not provided.
"""
if method not in ['scale', 'crop']:
raise ValueError(
"Unsupported thumb method '%s'" % method
)
query_params = {
"width": width,
"height": height,
"method": method
}
if not allow_remote:
query_params["allow_remote"] = False
if mxcurl.startswith('mxc://'):
return self._send(
"GET", mxcurl[6:],
query_params=query_params,
api_path="/_matrix/media/r0/thumbnail/",
return_json=False
)
else:
raise ValueError(
"MXC URL '%s' did not begin with 'mxc://'" % mxcurl
)
|
Get preview for URL.
Args:
url (str): URL to get a preview
ts (double): The preferred point in time to return
a preview for. The server may return a newer
version if it does not have the requested
version available.
|
def get_url_preview(self, url, ts=None):
"""Get preview for URL.
Args:
url (str): URL to get a preview
ts (double): The preferred point in time to return
a preview for. The server may return a newer
version if it does not have the requested
version available.
"""
params = {'url': url}
if ts:
params['ts'] = ts
return self._send(
"GET", "",
query_params=params,
api_path="/_matrix/media/r0/preview_url"
)
|
Get room id from its alias.
Args:
room_alias (str): The room alias name.
Returns:
Wanted room's id.
|
def get_room_id(self, room_alias):
"""Get room id from its alias.
Args:
room_alias (str): The room alias name.
Returns:
Wanted room's id.
"""
content = self._send("GET", "/directory/room/{}".format(quote(room_alias)))
return content.get("room_id", None)
|
Set alias to room id
Args:
room_id (str): The room id.
room_alias (str): The room wanted alias name.
|
def set_room_alias(self, room_id, room_alias):
"""Set alias to room id
Args:
room_id (str): The room id.
room_alias (str): The room wanted alias name.
"""
data = {
"room_id": room_id
}
return self._send("PUT", "/directory/room/{}".format(quote(room_alias)),
content=data)
|
Set the rule for users wishing to join the room.
Args:
room_id(str): The room to set the rules for.
join_rule(str): The chosen rule. One of: ["public", "knock",
"invite", "private"]
|
def set_join_rule(self, room_id, join_rule):
"""Set the rule for users wishing to join the room.
Args:
room_id(str): The room to set the rules for.
join_rule(str): The chosen rule. One of: ["public", "knock",
"invite", "private"]
"""
content = {
"join_rule": join_rule
}
return self.send_state_event(room_id, "m.room.join_rules", content)
|
Set the guest access policy of the room.
Args:
room_id(str): The room to set the rules for.
guest_access(str): Wether guests can join. One of: ["can_join",
"forbidden"]
|
def set_guest_access(self, room_id, guest_access):
"""Set the guest access policy of the room.
Args:
room_id(str): The room to set the rules for.
guest_access(str): Wether guests can join. One of: ["can_join",
"forbidden"]
"""
content = {
"guest_access": guest_access
}
return self.send_state_event(room_id, "m.room.guest_access", content)
|
Update the display name of a device.
Args:
device_id (str): The device ID of the device to update.
display_name (str): New display name for the device.
|
def update_device_info(self, device_id, display_name):
"""Update the display name of a device.
Args:
device_id (str): The device ID of the device to update.
display_name (str): New display name for the device.
"""
content = {
"display_name": display_name
}
return self._send("PUT", "/devices/%s" % device_id, content=content)
|
Deletes the given device, and invalidates any access token associated with it.
NOTE: This endpoint uses the User-Interactive Authentication API.
Args:
auth_body (dict): Authentication params.
device_id (str): The device ID of the device to delete.
|
def delete_device(self, auth_body, device_id):
"""Deletes the given device, and invalidates any access token associated with it.
NOTE: This endpoint uses the User-Interactive Authentication API.
Args:
auth_body (dict): Authentication params.
device_id (str): The device ID of the device to delete.
"""
content = {
"auth": auth_body
}
return self._send("DELETE", "/devices/%s" % device_id, content=content)
|
Bulk deletion of devices.
NOTE: This endpoint uses the User-Interactive Authentication API.
Args:
auth_body (dict): Authentication params.
devices (list): List of device ID"s to delete.
|
def delete_devices(self, auth_body, devices):
"""Bulk deletion of devices.
NOTE: This endpoint uses the User-Interactive Authentication API.
Args:
auth_body (dict): Authentication params.
devices (list): List of device ID"s to delete.
"""
content = {
"auth": auth_body,
"devices": devices
}
return self._send("POST", "/delete_devices", content=content)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.