async def real_init(): """ Runs async to avoid timeouts """ if tasks: return n = e = t = 0 list = await serverboards.maybe_await(serverboards.service.list()) print("Checking %d service status" % len(list)) # Launch all in parallel mtasks = [] for service in list: task = await curio.spawn(inserted_service, service) mtasks.append(task) for task in mtasks: t += 1 try: ok = await task.join() if ok: n += 1 except Exception as exc: import traceback traceback.print_exc() serverboards.log_traceback(exc) e += 1 await serverboards.info( "Service up stats -- UP: %d DOWN: %s NO INFO: %d TOTAL: %d" % (n, e, t - (n + e), t)) if e: await serverboards.error( "There were errors on %d up service checkers" % e)
async def remove_service(service, *args, **kwargs): uuid = service["uuid"] print("Remove service from periodic checks", uuid) tid = tasks.get(uuid) if tid: await tid.cancel() del tasks[uuid]
async def real_init(): """ Runs async to avoid timeouts """ if tasks: return n = e = t = 0 list = await serverboards.maybe_await(serverboards.service.list()) print("Checking %d service status" % len(list)) # Launch all in parallel mtasks = [] for service in list: task = await curio.spawn(inserted_service, service) mtasks.append(task) for task in mtasks: t += 1 try: ok = await task.join() if ok: n += 1 except Exception as exc: import traceback traceback.print_exc() serverboards.log_traceback(exc) e += 1 await serverboards.info( "Service up stats -- UP: %d DOWN: %s NO INFO: %d TOTAL: %d" % (n, e, t - (n + e), t)) if e: await serverboards.error( "There were errors on %d up service checkers" % e)
async def remove_service(service, *args, **kwargs): uuid = service["uuid"] print("Remove service from periodic checks", uuid) tid = tasks.get(uuid) if tid: await tid.cancel() del tasks[uuid]
def create_campaign(account_id, name, objective, status): account = AdAccount(account_id) campaign = Campaign(parent_id=account.get_id_assured()) campaign[Campaign.Field.name] = name campaign[Campaign.Field.objective] = objective campaign[Campaign.Field.configured_status] = status print(campaign.remote_create())
async def install(plugin_id): try: res = await curio.subprocess.check_output( ["s10s", "plugin", "install", "--format=json", plugin_id]) except curio.subprocess.CalledProcessError as e: print(e.output) raise return json_loads(res)
async def logout(): try: res = await curio.subprocess.check_output( ["s10s", "plugin", "logout", "--format=json"]) except curio.subprocess.CalledProcessError as e: print(e.output) raise return json_loads(res)
async def remove(plugin_id, action_id=None): try: res = await curio.subprocess.check_output( ["s10s", "plugin", "remove", plugin_id, "--format=json"]) except curio.subprocess.CalledProcessError as e: print(e.output) raise return json_loads(res)
async def login(email, password): try: res = await curio.subprocess.check_output( ["s10s", "plugin", "login", email, password, "--format=json"], stdin=None) except curio.subprocess.CalledProcessError as e: print(e.output) raise return json_loads(res)
async def search(*args, **kwargs): terms = list(args) + [ "%s:%s" % x for x in kwargs.items() if not x[0].startswith('-') ] await serverboards.debug("Searching for components with: %s" % terms) cmd = [ "s10s", "plugin", "search", "--format=json", *terms, "--fields=base,icon,icon64" ] print(cmd) result = await curio.subprocess.check_output(cmd) return json_loads(result)
async def enable(plugin_id, action_id=None, enabled=True): try: action = None if enabled: action = "enable" else: action = "disable" res = await curio.subprocess.check_output( ["s10s", "plugin", action, plugin_id, "--format=json"]) except curio.subprocess.CalledProcessError as e: print(e.output) raise return json_loads(res)
def send_sync(): port = settings.get("port") ssl = settings.get("ssl") if port or ssl: if port == '465' or ssl: port = port or '465' smtp = smtplib.SMTP_SSL(settings["servername"], int(port)) else: smtp = smtplib.SMTP(settings["servername"], int(port)) else: smtp = smtplib.SMTP(settings["servername"]) if settings.get("username"): print("Login as ", repr(settings)) smtp.login(settings.get("username"), settings.get("password_pw")) smtp.sendmail(settings["from"], email, msg.as_string()) smtp.close()
def send_sync(): port = settings.get("port") ssl = settings.get("ssl") if port or ssl: if port == '465' or ssl: port = port or '465' smtp = smtplib.SMTP_SSL(settings["servername"], int(port)) else: smtp = smtplib.SMTP(settings["servername"], int(port)) else: smtp = smtplib.SMTP(settings["servername"]) if settings.get("username"): print("Login as ", repr(settings)) smtp.login(settings.get("username"), settings.get("password_pw")) smtp.sendmail(settings["from"], email, msg.as_string()) smtp.close()
def schema(config, table=None): print("Get table ", config, table) if not table: return ["random"] if table == "random": return { "columns": [ {"name": "random", "description": "The random number"}, {"name": "min", "description": "The minimum value"}, {"name": "max", "description": "The maximum value"} ], "description": "A table with a single random number. Can be \ tweaked to be between a max a min." } raise Exception("unknown-table")
async def check_updates(*plugins): """ Checks for updates. If no plugins passed, checks them all. """ try: await curio.subprocess.check_output( ["s10s", "plugin", "check", *plugins, "--format=json"]) res = await curio.subprocess.check_output( ["s10s", "plugin", "list", "--format=json"]) res = json_loads(res) if plugins: # Not the most efficient. But works. Might be fixed with a "plugin info" command. res = [x for x in res if x["id"] in plugins] except curio.subprocess.CalledProcessError as e: print(e.output) raise return res
def schema(config, table=None): print("Get table ", config, table) if not table: return ["random"] if table == "random": return { "columns": [{ "name": "random", "description": "The random number" }, { "name": "min", "description": "The minimum value" }, { "name": "max", "description": "The maximum value" }], "description": "A table with a single random number. Can be \ tweaked to be between a max a min." } raise Exception("unknown-table")
def create_creative(account_id, name, caption, message, link, imagehash, page_id): from facebookads.adobjects.adcreativelinkdata import AdCreativeLinkData from facebookads.adobjects.adcreativeobjectstoryspec \ import AdCreativeObjectStorySpec link_data = AdCreativeLinkData() link_data[AdCreativeLinkData.Field.message] = message link_data[AdCreativeLinkData.Field.link] = link link_data[AdCreativeLinkData.Field.caption] = caption link_data[AdCreativeLinkData.Field.image_hash] = imagehash object_story_spec = AdCreativeObjectStorySpec() object_story_spec[AdCreativeObjectStorySpec.Field.page_id] = page_id object_story_spec[AdCreativeObjectStorySpec.Field.link_data] = link_data creative = AdCreative(parent_id=account_id) creative[AdCreative.Field.name] = name creative[AdCreative.Field.object_story_spec] = object_story_spec creative.remote_create() print(creative) return creative
def test(): account = AdAccount(settings.AD_USER) adsets = account.get_ad_sets(fields=[ AdSet.Field.name, AdSet.Field.bid_info, AdSet.Field.configured_status, AdSet.Field.daily_budget, AdSet.Field.targeting, ]) print(adsets) users = account.get_ad_users() print(users) return for i in get_possible_insights(): print(i) print(get_insights(i["value"])) # print() continue
async def test_async(): print("Start debug") global settings settings = yaml.load(open("config.yaml")) # { # "servername" : "mail.serverboards.io", # "port" : "", # "from" : "*****@*****.**", # "username" : "", # "password_pw" : "" # } sea = await send_email_action( "*****@*****.**", "This is a test from s10s test", "The body of the test", message_id="*****@*****.**", ) print("email action", sea) assert sea == {"sent": True} se = await send_email( user={"email": "*****@*****.**"}, config={}, message={ "subject": "This is a test message", "body": "Body of the test message\n\nAnother line", "extra": {} }, test=True, message_id="*****@*****.**", ) print("email to user", se) assert se print("Done") await serverboards.curio.sleep(2) sys.exit(0)
async def test_async(): print("Start debug") global settings settings = yaml.load(open("config.yaml")) # { # "servername" : "mail.serverboards.io", # "port" : "", # "from" : "*****@*****.**", # "username" : "", # "password_pw" : "" # } sea = await send_email_action( "*****@*****.**", "This is a test from s10s test", "The body of the test", message_id="*****@*****.**", ) print("email action", sea) assert sea == {"sent": True} se = await send_email( user={"email": "*****@*****.**"}, config={}, message={ "subject": "This is a test message", "body": "Body of the test message\n\nAnother line", "extra": {} }, test=True, message_id="*****@*****.**", ) print("email to user", se) assert se print("Done") await serverboards.curio.sleep(2) sys.exit(0)
import datetime from facebookads.api import FacebookAdsApi from facebookads.adobjects.adaccount import AdAccount # from facebookads.adobjects.aduser import AdUser from facebookads.adobjects.campaign import Campaign from facebookads.adobjects.adsinsights import AdsInsights from facebookads.adobjects.adset import AdSet from facebookads.adobjects.ad import Ad from facebookads.adobjects.adcreative import AdCreative from serverboards_aio import print try: import settings FacebookAdsApi.init(settings.APP_ID, settings.APP_SECRET, settings.ACCESS_TOKEN) print("Using default config from settings.py") except Exception: pass # @serverboards.rpc_method # def get_accounts(): # def decorate(x): # return { # "value": x["id"], # "name": x["name"] # } # me = AdUser(settings.AD_USER) # return [decorate(x) for x in me.get_ad_accounts(["id", "name"])] @serverboards.rpc_method
async def test(): print(await search(type="screen"))
def extractor(config, table, quals, columns): print("Extractor", config, table, quals, columns) if table == "random": return extractor_random(quals, columns) raise Exception("unknown-table")
@serverboards.rpc_method def extractor(config, table, quals, columns): print("Extractor", config, table, quals, columns) if table == "random": return extractor_random(quals, columns) raise Exception("unknown-table") def extractor_random(quals, columns): min = get_qual(quals, "min", "=", 0) max = get_qual(quals, "max", "=", 1) return { "columns": ["random", "min", "max"], "rows": [[min + random.random() * (max - min), min, max]] } def get_qual(quals, col, op, default): for q in quals: if q[0] == col and q[1] == op: return q[2] return default if __name__ == '__main__': # serverboards.set_debug() print("Starting", file=sys.stderr) serverboards.loop()
async def get_account(config): service = await serverboards.service.get(config["service"]) print(service) config = service["config"] return AdAccount(config["ad_user"])
def extractor(config, table, quals, columns): print("Extractor", config, table, quals, columns) if table == "random": return extractor_random(quals, columns) raise Exception("unknown-table")
@serverboards.rpc_method def extractor(config, table, quals, columns): print("Extractor", config, table, quals, columns) if table == "random": return extractor_random(quals, columns) raise Exception("unknown-table") def extractor_random(quals, columns): min = get_qual(quals, "min", "=", 0) max = get_qual(quals, "max", "=", 1) return { "columns": ["random", "min", "max"], "rows": [[min + random.random() * (max - min), min, max]] } def get_qual(quals, col, op, default): for q in quals: if q[0] == col and q[1] == op: return q[2] return default if __name__ == '__main__': # serverboards.set_debug() print("Starting", file=sys.stderr) serverboards.loop()