def send_print_notification_pushbullet(_print):
    if not _print.printer.user.has_valid_pushbullet_token():
        return

    pb = Pushbullet(_print.printer.user.pushbullet_access_token)

    title = 'The Spaghetti Detective - Print job notification'
    link = site.build_full_url('/')
    body = f"Your print job {_print.filename} {'has been canceled' if _print.is_canceled() else 'is done'} on printer {_print.printer.name}."
    file_url = None
    try:
        file_url = _print.printer.pic['img_url']
        if not ipaddress.ip_address(urlparse(file_url).hostname).is_global:
            pb.upload_file(requests.get(file_url).content, 'Snapshot.jpg')
    except:
        pass

    try:
        if file_url:
            pb.push_file(file_url=file_url,
                         file_name="Snapshot.jpg",
                         file_type="image/jpeg",
                         body=body,
                         title=title)
        else:
            pb.push_link(title, link, body)
    except (PushError, PushbulletError) as e:
        LOGGER.error(e)
def send_print_notification_pushbullet(_print, event_type=None):
    if not _print.printer.user.has_valid_pushbullet_token():
        return

    pb = Pushbullet(_print.printer.user.pushbullet_access_token)

    title = 'The Spaghetti Detective - Print job notification'
    link = site.build_full_url('/')
    body = get_notification_body(_print, event_type=event_type)
    file_url = None
    try:
        file_url = _print.poster_url
        if not settings.SITE_IS_PUBLIC:
            pb.upload_file(requests.get(file_url).content, 'Snapshot.jpg')
    except:
        pass

    try:
        if file_url:
            pb.push_file(file_url=file_url,
                         file_name="Snapshot.jpg",
                         file_type="image/jpeg",
                         body=body,
                         title=title)
        else:
            pb.push_link(title, link, body)
    except (PushError, PushbulletError) as e:
        LOGGER.error(e)
def send_failure_alert_pushbullet(printer, is_warning, print_paused):
    if not printer.user.has_valid_pushbullet_token():
        return

    pausing_msg = ''
    if print_paused:
        pausing_msg = 'Printer is paused.'
    elif printer.action_on_failure == Printer.PAUSE and is_warning:
        pausing_msg = 'Printer is NOT paused because The Detective is not very sure about it.'

    pb = Pushbullet(printer.user.pushbullet_access_token)
    title = 'The Spaghetti Detective - Your print {} on {} {}.'.format(
        printer.current_print.filename or '',
        printer.name,
        'smells fishy' if is_warning else 'is probably failing')
    link = site.build_full_url('/')
    body = '{}\nGo check it at: {}'.format(pausing_msg, link)

    try:
        file_url = None
        try:
            file_url = printer.pic['img_url']
            if not ipaddress.ip_address(urlparse(file_url).hostname).is_global:
                pb.upload_file(requests.get(file_url).content, 'Detected Failure.jpg')
        except:
            pass

        if file_url:
            pb.push_file(file_url=file_url, file_name="Detected Failure.jpg", file_type="image/jpeg", body=body, title=title)
        else:
            pb.push_link(title, link, body)
    except PushError as e:
        LOGGER.error(e)
    except PushbulletError as e:
        LOGGER.error(e)
    def push_chart(self):
        """ Pushes the chart to a Pushbullet account. """

        pb = Pushbullet(config.PB_API_KEY)

        with open('./today.jpg', 'rb') as pic:
            file_data = pb.upload_file(pic, 'today.jpg')

        pb.push_file(**file_data)
Exemple #5
0
 def _send_push_attachment(self, api_key, text, file=None):
     pb = Pushbullet(api_key)
     # If the file exist than open and push, otherwise attach an error message to the content
     if os.path.exists(file):
         with open(file, "rb") as fil:
             file_data = pb.upload_file(fil, text)
         pb.push_file(**file_data)
     else:
         print('Error: File does not exists. file:' + file)
def push_file(filename):
	if is_device_connected(DEVICE_MAC):
		print "Device is connected, not sending"
		return
	print "Sending", filename

	pushbullet = Pushbullet(PUSHBULLET_API_KEY)
	my_device = pushbullet.get_device(PUSHBULLET_DEVICE_NAME)
	file_data = pushbullet.upload_file(open(filename, "rb"), filename)
	pushbullet.push_file(device = my_device, **file_data)
	print "Sent!"
Exemple #7
0
def push_file(filename):
    if is_device_connected(DEVICE_MAC):
        print "Device is connected, not sending"
        return
    print "Sending", filename

    pushbullet = Pushbullet(PUSHBULLET_API_KEY)
    my_device = pushbullet.get_device(PUSHBULLET_DEVICE_NAME)
    file_data = pushbullet.upload_file(open(filename, "rb"), filename)
    pushbullet.push_file(device=my_device, **file_data)
    print "Sent!"
Exemple #8
0
class PushbullectHelper():
    def __init__(self):
        self.pb = Pushbullet(api_key)
        self.iphone = self.pb.devices[0]
        self.device = self.pb.devices

    def sendnote(self, title, str):
        self.pb.push_note(title, str, device=self.iphone)

    def sendall(self, title, str):
        self.pb.push_note(title, str)

    def sendfile(self, file, name):
        filedata = self.pb.upload_file(file, name)
        self.pb.push_file(**filedata)
Exemple #9
0
def push_file(filename):
    auth_key = _get_pb_authKey()
    pb = Pushbullet(auth_key)  # authenticate

    with open(filename, 'rb') as file_to_push:
        file_data = pb.upload_file(file_to_push, filename)

    push_data = pb.push_file(**file_data)
 def send_pushbullet(self):
     pb = Pushbullet(self.pushbullet_token)
     if self.file_path is not None:
         with open(self.file_path, "rb") as f:
             file_data = pb.upload_file(f, f.name.replace("-", ""))
             response = pb.push_file(**file_data)
     else:
         pb.push_note("Motion detected!", "Motion detected, could not find preview image")
     print "PiSN: Pushbullet notification succesfully pushed"
    def on_file_received(self, file):
        print "File received " + file
        #super(MyHandler, self).on_file_sent(self, file)
        pb = Pushbullet(api_key)

        with open(file, "rb") as pic:
            file_data = pb.upload_file(pic, file)

        push = pb.push_file(**file_data)
Exemple #12
0
def on_message(client, userdata, msg):
    pb = Pushbullet("SECRET TOKEN")
    push = pb.push_note("Evento", "Se detecto un evento en la puerta")
    archivo = time.strftime("%Y%m%d%H%M%S", time.localtime())+".png"
    print("Evento detectado")
    camara = CamaraIP('url_camara')
    camara.capturar(archivo) 
    print("Enviando imagen ",archivo)
    with open(archivo, "rb") as pic:
        file_data = pb.upload_file(pic, archivo)
    push = pb.push_file(**file_data)   
def send_image():

    if len(sys.argv) < 2:
        print('Missing image in arguments')
        return

    pb = Pushbullet(PUSHBULLET_API_KEY)
    image = sys.argv[1]
    with open(image, "rb") as pic:
        file_data = pb.upload_file(pic, "photo.jpg")

    device = pb.get_device('S10')
    push = pb.push_file(**file_data, device=device)
    def call_pushbullet(
        self,
        access_token: str,
        title: str,
        body: str,
        link: str,
        file_url: str,
    ) -> None:
        pb = Pushbullet(access_token)
        try:
            if not settings.SITE_IS_PUBLIC:
                pb.upload_file(requests.get(file_url).content, 'Snapshot.jpg')
        except:
            pass

        if file_url:
            pb.push_file(file_url=file_url,
                         file_name="Snapshot.jpg",
                         file_type="image/jpeg",
                         body=body,
                         title=title)
        else:
            pb.push_link(title, link, body)
def send_push(file):
    try:
        urllib3.disable_warnings()
        pb = Pushbullet(API_KEY)
        #push = pb.push_note(pb.devices[3]['iden'],'Alarm', 'Motion detected')
        push = pb.push_note('Alarm', 'Motion detected')
        print "push-uploading file.."
        with open(file, 'rb') as vid:
            file_data = pb.upload_file(vid, 'video.mkv')
        push = pb.push_file(**file_data)
        # only for debug:
        #pushes = pb.get_pushes()
        #latest = pushes[0]
        #print latest
    except Exception, error:
        print "Error in send_push: " + str(error)
Exemple #16
0
def sendtophone():
    dir = r"/home/pi/weather-station/data/"
    filename = str(date.today())

    humidity, pressure, ambient_temperature = bme280_output.read_all()
    temperature = round(ambient_temperature,2)
    humidity = round(humidity,2)
    tempdata = str(temperature)
    humdata = str(humidity)
    pb = Pushbullet('o.SpLVyGfhBJGKv9E8UxPs7sWsO7kyzcwi')

    with open(os.path.join(dir,filename+'.png'),"rb") as pic:
                file_data = pb.upload_file(pic, "test.png")
                
    push = pb.push_note("Raspberry Pi","°C :"+ tempdata+ "     Humidity: " + humdata +"%")        
    push = pb.push_file(**file_data)        
Exemple #17
0
def pushbullet_listening():
    week = ['mon','tue','wed','thu','fri','sat','sun']
    day_of_week = week[datetime.today().weekday()]
    hour_of_day = datetime.now().hour
    minute_of_day = datetime.now().minute

    title = 'Khaleesi notifications'
    now_time = '{hour}:{minute}:00'.format(hour=hour_of_day, minute=minute_of_day)

    list_notifications = {
        'start_time': {
            'text': 'Buen día. Es hora de comenzar a trabajar. No olvides activar tus tareas.',
            'filter': {'start_time': now_time},
            'type': 'note'
         },
        'lunch_time': {
            'text': 'Hora de comer ! Recuerda pausar tus tareas activas.',
            'filter': {'lunch_time': now_time},
            'type': 'image'
         },
        'end_time': {
            'text': 'Tu día parece haber terminado. Buen trabajo. Recuerda que a las 6pm todas las tareas activas se pausarán automáticamente.',
            'filter': {'end_time': now_time},
            'type': 'link',
            'url': 'http://khaleesi.unisem.mx/admin/track/tarea/'
         }
    }

    for profile in UserProfile.objects.filter(Q(**{day_of_week: True}) & Q(token__isnull=False)):
        try:
            pb = Pushbullet(profile.token)
            #print profile.user
            for notification in list_notifications.keys():
                if UserProfile.objects.filter(id=profile.id).filter(Q(**list_notifications[notification]['filter'])).count() > 0:
                    if list_notifications[notification]['type'] == 'note':
                        push = pb.push_note(title, list_notifications[notification]['text'])
                    elif list_notifications[notification]['type'] == 'link':
                        push = pb.push_link(title, url=list_notifications[notification]['url'], body=list_notifications[notification]['text'])
                    elif list_notifications[notification]['type'] == 'image':
                        push = pb.push_file(file_url=get_url_image(), file_name=title, file_type='image/jpeg', body=list_notifications[notification]['text'])
                    print push
        except Exception as e:
            #print 'Error: ', e
            pass
Exemple #18
0
print(pb.devices)

#Get a device
dev = pb.get_device("Galaxy S7 Edge")

#1. Push Notification
push = dev.push_note("Alert!", "This PUSH-notification sent from Raspberry!")

# push is a dictionary containing the data returned by the Pushbullet API.
print('A dictionalry after 1:')
print(push)

#2. SMS-message
push = pb.push_sms(dev, "+31612345678", "This SMS sent from Raspberry!")
print('A dictionalry after 2:')
print(push)

#3. Push a file from file system
with open("thief.jpg", "rb") as pic:
    file_data = pb.upload_file(pic, "picture.jpg")
push = pb.push_file(**file_data)
print('A dictionalry after 3:')
print(push)

#4. Push a file already uploaded somewhere
push = pb.push_file(file_url="https://i.imgur.com/IAYZ20i.jpg",
                    file_name="cat.jpg",
                    file_type="image/jpeg")
print('A dictionalry after 4:')
print(push)
class SnapshotPipeline(Pipeline):
    def __init__(self):
        super(SnapshotPipeline, self).__init__('snap_pipe')

        self.file_source = ""
        self.pb = Pushbullet('o.cJzinoZ3SdlW7JxYeDm7tbIrueQAW5aK')

        self.create_snapshot()

        bus = self.pipe.get_bus()
        bus.add_signal_watch()
        bus.connect('message', self.on_message_cb, None)

    def create_snapshot(self):
        self.appsrc = Gst.ElementFactory.make('appsrc', 'snapsrc')
        self.pipe.add(self.appsrc)

        jpegenc = Gst.ElementFactory.make('jpegenc', 'jpegenc')
        self.pipe.add(jpegenc)

        self.filesink = Gst.ElementFactory.make('filesink', 'jpegfilesink')
        self.pipe.add(self.filesink)

        self.appsrc.link(jpegenc)
        jpegenc.link(self.filesink)

    def send_snapshot(self):
        dtime = Gst.DateTime.new_now_local_time()
        g_datetime = dtime.to_g_date_time()
        timestamp = g_datetime.format("%F_%H%M%S")
        timestamp = timestamp.replace("-", "")
        filename = "sshot_" + timestamp + ".jpg"
        self.file_source = filename
        print("Filename : %s" % filename)

        self.filesink.set_property('location', filename)
        self.filesink.set_property('async', False)

        self.pipe.set_state(Gst.State.PLAYING)

    def on_message_cb(self, bus, msg, data):
        t = msg.type
        if t == Gst.MessageType.ERROR:
            name = msg.src.get_path_string()
            err, debug = msg.parse_error()
            print(
                "Snapshot pipeline -> Error received : from element %s : %s ."
                % (name, err.message))
            if debug is not None:
                print("Additional debug info:\n%s" % debug)

            self.pipe.set_state(Gst.State.NULL)
            self.file_source = ""

        elif t == Gst.MessageType.WARNING:
            name = msg.src.get_path_string()
            err, debug = msg.parse_warning()
            print(
                "Snapshot pipeline -> Warning received : from element %s : %s ."
                % (name, err.message))
            if debug is not None:
                print("Additional debug info:\n%s" % debug)

        elif t == Gst.MessageType.EOS:
            print("Snapshot End-Of-Stream received")
            print(datetime.now())
            print("")
            self.pipe.set_state(Gst.State.NULL)

            if self.file_source != "":
                with open(self.file_source, 'rb') as pic:
                    file_data = self.pb.upload_file(pic, self.file_source)
                for key in file_data.keys():
                    print("%s in File data of value : %s" %
                          (key, file_data[key]))
                push = self.pb.push_file(title="Motion detected", **file_data)
                print(push)
                self.file_source = ""
Exemple #20
0
class PushbulletSkill(MycroftSkill):
    """
    A Skill to send message using Pushbullet
    """
 

    def __init__(self):
        super(PushbulletSkill, self).__init__(name="PushbulletSkill")

	self.audio_effects = "/opt/mycroft/skills/PushbulletSkill/"
	self.enable_fallback = False
        self._setup()
        try:
            self.settings.set_changed_callback(self._force_setup)
        except BaseException:
            LOGGER.debug(
                'No auto-update on changed settings (Outdated version)')

        try:
            self.settings.set_changed_callback(self._force_setup)
        except BaseException:
            LOGGER.debug(
                'No auto-update on changed settings (Outdated version)')




    def _setup(self, force=False):
        if self.settings is not None:
             self.api_key = self.settings.get('api_key')
            

	self.photo_script = "/opt/mycroft/skills/PushbulletSkill/script/photo.py"
	self.photo_img = "/tmp/photo.png"
	self.help_audio = "/tmp/help"

	"""
	Register Mycroft device to Pushbullet
	"""
	self.pb = Pushbullet(self.api_key)
	"""
	Get the contacts list from Pushbullet Mycroft device registered
	"""
	self.contactspb = self.pb.chats
	self.devicespb = self.pb.devices

	self.contacts={}
	for i in range(len(self.contactspb)):	
	    row_contact = str(self.contactspb[i])
	    name = row_contact.split("'",1)[1].split("'")[0]
	    name = name.replace(" ","").lower()
	    email = row_contact.split("<",1)[1].split(">")[0]
	    self.contacts[name] = self.contactspb[i]

	self.devices={}
	for i in range(len(self.devicespb)):	
	    row_device = str(self.devicespb[i])
	    name = row_device.split("'",1)[1].split("'")[0]
	    name = name.replace(" ","").lower()
	    self.devices[name] = self.devicespb[i]

    def initialize(self):
        self.load_data_files(dirname(__file__))
        self.load_regex_files(join(dirname(__file__), 'regex', self.lang))

        intent = IntentBuilder("PushMessageIntent")\
        	.require("PushMessageKeyword")\
		.require("Contact")\
		.require("Message")\
		.build()
        self.register_intent(intent, self.handle_pushmessage)

        intent = IntentBuilder("PushMeMessageIntent")\
        	.require("PushMessageKeyword")\
		.require("MeKeyword")\
		.require("SelfMessage")\
		.build()
        self.register_intent(intent, self.handle_push_me_message)

        intent = IntentBuilder("PushPhotoIntent")\
		.require("PushPhotoKeyword")\
		.build()
        self.register_intent(intent, self.handle_pushphoto)

        intent = IntentBuilder("PushHelpIntent")\
		.require("PushHelpKeyword")\
		.build()
        self.register_intent(intent, self.handle_help)

    def handle_pushmessage(self, message):
        try:
            contact = message.data.get("Contact").lower()
            if contact in self.contacts:
		"""
    		Evaluate a exact contact to send message using Pushbullet
    		"""
                chat = self.contacts.get(contact)
                msg = message.data.get("Message")
	   	push = self.pb.push_note("Message from Mycroft",msg, chat=chat)
	   	data = {"contact": contact}
	   	self.speak_dialog("push.message",data)
            elif contact in self.devices:
		"""
    		Evaluate a exact device to send message using Pushbullet
    		"""
                device = self.devices.get(contact)
                msg = message.data.get("Message")
	   	push = self.pb.push_note("Message from Mycroft",msg, device=device)
	   	data = {"contact": contact}
	   	self.speak_dialog("push.device",data)
	    else:
		"""
    		Evaluate a similar contact to send message using Pushbullet
    		"""
		matching_contact = [s for s in self.contacts if contact in s]
		matching_device = [d for d in self.devices if contact in d]

		matching_contact = str(matching_contact)
		matching_device = str(matching_device)

		if len(matching_contact) > 2:
			name_match = matching_contact.split("'",1)[1].split("'")[0]
			chat = self.contacts.get(name_match)
	                msg = message.data.get("Message")
		   	push = self.pb.push_note("Message from Mycroft",msg, chat=chat)
		   	data = {"contact": name_match}
		   	self.speak_dialog("push.message",data)
		elif len(matching_device) > 2:
			name_match = matching_device.split("'",1)[1].split("'")[0]
			device = self.devices.get(name_match)
	                msg = message.data.get("Message")
			full_name = str(device).split("'")
			full_name = full_name[1]
		   	push = self.pb.push_note("Message from Mycroft",msg, device=device)
		   	data = {"contact": full_name}
		   	self.speak_dialog("push.device",data)

        except Exception as e:
	    data = {"contact": contact}
	    self.speak_dialog("processing.pushmessage",data)


    def handle_push_me_message(self, message):

	msg = message.data.get("SelfMessage")
   	push = self.pb.push_note("Message from Mycroft",msg)
   	self.speak_dialog("push.self.message")


    def	handle_pushphoto(self, message):
	"""
	Run photo_cmd (photo.py) outside Mycroft Virtual Environment 
    	"""
	photo_cmd = "/usr/bin/python2.7 " + self.photo_script
	os.system(photo_cmd)

	time.sleep(1)
	with open(self.photo_img,"rb") as png:
	    file_data = self.pb.upload_file(png, "photo.png")
        #chat = self.chat
  	push = self.pb.push_file(**file_data)


    def	handle_help(self, message):
	"""
	Record 10 seconds to help_audio_file.mp3 file
    	"""
	self.speak_dialog("push.help")
	time.sleep(7)
	p = play_wav(self.audio_effects+"ding.wav")
	p.communicate()


	r = record(self.help_audio+".wav",10,16000,1)
	r.communicate()

	p = play_wav(self.audio_effects+"dong.wav")
	p.communicate()

	with open(self.help_audio+".wav","rb") as mp3:
	    file_data = self.pb.upload_file(mp3, "help_audio_file.wav")
	chat = self.pb.devices
  	push = self.pb.push_file(**file_data)
	self.speak_dialog("push.help.send")

	
    def stop(self):
        pass
Exemple #21
0
class PushBulletAPI(Thread):
    '''
    api_key has to be get from https://www.pushbullet.com/#settings/account
    Note:
    in the __init_ one can specify the channel that wants the communication to
    go and all comunitcations will go directly to that channel: No need to
    specify in the queue_push_text and queue_push_file functions the channel
    '''

    def __init__(self, api_key, channel_tag=None):

        Thread.__init__(self)
        self.pb = Pushbullet(api_key)

        self.text_queue = Queue()
        self.file_queue = Queue()
        self._mystop = False

        if channel_tag is not None:
            try:
                self.channel = self.get_channel(channel_tag)
            except:
                print("[ERROR] Could not load PushBullet channel:  " +
                      str(channel_tag))
                self.channel = None
        else:
            self.channel = None

    def queue_push_text(self, body, title=socket.gethostname(), channel=None):
        if self.channel is not None and channel is None:
            channel = self.channel
        self.text_queue.put({"title": title, "body": body, "channel": channel})

    def queue_push_file(self, filename, channel=None):
        if self.channel is not None and channel is None:
            channel = self.channel
        self.file_queue.put({"filename": filename, "channel": channel})

    def _push_text(self, title, body, channel=None):
        if channel is None:
            return self.pb.push_note(title, body)
        else:
            return self.pb.push_note(title, body, channel=channel)

    def _push_link(self, title, body, channel=None):
        if channel is None:
            return self.pb.push_note(title, body)
        else:
            return self.pb.push_note(title, body, channel=channel)

    def _push_file(self, filename, channel=None):
        path, fn = os.path.split(filename)
        with open(filename, "rb") as pic:
            file_data = self.pb.upload_file(pic, fn)

        if channel is None:
            return self.pb.push_file(**file_data)
        else:
            return self.pb.push_file(**file_data, channel=channel)

    def get_all_channels(self):
        return self.pb.channels

    def get_channel(self, channel_name):
        return self.pb.get_channel(channel_name)

    def mystop(self):
        self._mystop = True

    def run(self):
        while not self._mystop or not self.text_queue.empty() or not self.file_queue.empty():
            while not self.text_queue.empty():
                item = self.text_queue.get()
                self._push_text(item["title"], item["body"],
                                channel=item["channel"])

            while not self.file_queue.empty():
                item = self.file_queue.get()
                self._push_file(item["filename"], channel=item["channel"])

            tm.sleep(1)
Exemple #22
0
def download(link, newdevice, video, delete):
    """Download a youtube video or playlist
    in best audio and video quality
    by providing a link, and then send to the
    preffered device, or override it with `--newdevice`
    option.

    Provide the device name for `--newdevice` in quotes for e.g. "OnePlus One".

    Please run `moboff initialise` if this is your first time.
    """
    if os.path.exists('data.txt'):
        with open('data.txt') as json_file:
            data = json.load(json_file)
            for p in data['user']:
                api_key = p['api_key']
                device = p['device']
    else:
        click.secho("Please run `moboff initialise` first.",
                    fg='red',
                    bold=True)
        quit()

    os.chdir('Music')

    if video is True:
        downloadcommand = [
            "youtube-dl", "--metadata-from-title", "%(artist)s - %(title)s",
            "-f", "bestvideo+bestaudio", "--add-metadata", "--output",
            "%(artist)s - %(title)s.%(ext)s", link
        ]
    else:
        downloadcommand = [
            "youtube-dl", "--metadata-from-title", "%(artist)s - %(title)s",
            "--extract-audio", "--audio-format", "mp3", "--audio-quality", "0",
            "--add-metadata", "--output", "%(artist)s - %(title)s.%(ext)s",
            link
        ]

    try:
        subprocess.check_output(downloadcommand, stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError:
        print(
            "Please check your URL, it shouldn't be a private playlist link (eg liked videos)"
        )
        quit()

    click.secho("File successfully downloaded.", fg="green", bold=True)
    types = ('*.mp3', '*.mp4', '*.mkv')
    list_of_files = []
    for files in types:
        list_of_files.extend(glob.glob(files))

    recent_download = max(list_of_files, key=os.path.getctime)

    print("File to send : {0}".format(recent_download))

    pb = Pushbullet(api_key)
    phone = device

    if (newdevice):
        newdevice = "Device('{0}')".format(newdevice)
        click.secho("Overriding preffered device : {0} with given device : {1}"
                    ).format(device, newdevice)
        phone = newdevice

    with open(recent_download, "rb") as song:
        file_data = pb.upload_file(song, recent_download)

    print("Now sending the file to {0}".format(phone))
    push = pb.push_file(**file_data)

    if (delete):
        os.remove(recent_download)
Exemple #23
0
pb = Pushbullet("")
pb.push_note("ONLINE", "Nest Pension Monitor Online.")

print("Pension Monitor - Monitoring")

while True:
    loader.loading()
    time.sleep(60)
    try:
        a.getData()
        if links != a.links:
            print("New PDFs Found")
            links = a.links.copy()
            pb.push_note("New Nest Data")
            try:
                a.loadData()
                with open("Current_Data.png") as f:
                    lastest_file = pb.upload_file(f, "LatestNestData.png")
                
                pb.push_file(**lastest_file)
            except:
                pass
    except:
        print("Failed")
        try:
            pb.push_note("Nest Script Crashed","")
        except:
            pass

pb.push_note("Nest Script Crashed","")
Exemple #24
0
class SnapshotPipeline(Pipeline):
    def __init__(self):
        super(SnapshotPipeline, self).__init__('snap_pipe')
        
        self.file_source = ""
        self.pb = Pushbullet('o.cJzinoZ3SdlW7JxYeDm7tbIrueQAW5aK')
        
        self.create_snapshot()
        
        bus = self.pipe.get_bus()
        bus.add_signal_watch()
        bus.connect('message', self.on_message_cb, None)
        
    def create_snapshot(self):
        self.appsrc = Gst.ElementFactory.make('appsrc', 'snapsrc')
        self.pipe.add(self.appsrc)
        
        jpegenc = Gst.ElementFactory.make('jpegenc', 'jpegenc')
        self.pipe.add(jpegenc)
        
        self.filesink = Gst.ElementFactory.make('filesink', 'jpegfilesink')
        self.pipe.add(self.filesink)
        
        self.appsrc.link(jpegenc)
        jpegenc.link(self.filesink)
        
    def send_snapshot(self):
        dtime = Gst.DateTime.new_now_local_time()
        g_datetime = dtime.to_g_date_time()
        timestamp = g_datetime.format("%F_%H%M%S")
        timestamp = timestamp.replace("-", "")
        filename = "sshot_" + timestamp + ".jpg"
        self.file_source = filename
        print("Filename : %s" % filename)
        
        self.filesink.set_property('location', filename)
        self.filesink.set_property('async', False)
        
        self.pipe.set_state(Gst.State.PLAYING)
        
        
    def on_message_cb(self, bus, msg, data):
        t = msg.type
        if t == Gst.MessageType.ERROR:
            name = msg.src.get_path_string()
            err, debug = msg.parse_error()
            print("Snapshot pipeline -> Error received : from element %s : %s ." % (name, err.message))
            if debug is not None:
                print("Additional debug info:\n%s" % debug)
              
            self.pipe.set_state(Gst.State.NULL)
            self.file_source = ""
            
        elif t == Gst.MessageType.WARNING:
            name = msg.src.get_path_string()
            err, debug = msg.parse_warning()
            print("Snapshot pipeline -> Warning received : from element %s : %s ." % (name, err.message))
            if debug is not None:
                print("Additional debug info:\n%s" % debug)
            
        elif t == Gst.MessageType.EOS:
            print("Snapshot End-Of-Stream received")
            print(datetime.now())
            print("")
            self.pipe.set_state(Gst.State.NULL)
            
            if self.file_source != "":
                with open(self.file_source, 'rb') as pic:
                    file_data = self.pb.upload_file(pic, self.file_source)
                for key in file_data.keys():
                    print("%s in File data of value : %s" % (key , file_data[key]))
                push = self.pb.push_file(title="Motion detected", **file_data)
                print(push)
                self.file_source = ""
Exemple #25
0
def download(link, newdevice, video, delete, send):
    """Download a youtube video or playlist
    in best audio and video quality
    by providing a link, and then send to the
    preferred device, or override it with `--newdevice`
    option.

    Provide the device name for `--newdevice` in quotes for e.g. "OnePlus One".

    Please run `moboff initialise` if this is your first time.
    """
    os.chdir(real_path_of_MobOff)

    if os.path.exists('moboff_cfg.json'):
        with open('moboff_cfg.json') as json_file:
            data = json.load(json_file)
            api_key = data['user']['api_key']
            device = data['user']['device']
            directory = data['user']['directory']
    else:
        click.secho("Please run `moboff initialise` first.",
                    fg='red',
                    bold=True)
        quit()

    try:
        pb = Pushbullet(api_key)
    except pushbullet.errors.InvalidKeyError:
        click.secho(
            "API key you previously entered is no longer valid. Please rerun moboff initialise."
        )
        quit()

    phone = device

    if newdevice:
        click.secho(
            "Overriding preferred device : {0} with given device : {1}".format(
                device, newdevice))
        phone = newdevice

    try:
        to_device = pb.get_device(phone)
    except pushbullet.errors.PushbulletError:
        if newdevice:
            click.secho(
                "{0} isn't setup with Pushbullet. "
                "Please either set it up or check the spelling of entered device"
                .format(newdevice))
        else:
            click.secho(
                "The default device you entered initially doesn't exist anymore. "
                "Please rerun moboff initialise.")
        quit()

    try:
        os.chdir(directory)
    except OSError:
        click.secho(
            "The directory previously selected to download music can't be accessed."
            " Please rerun moboff initialise.")
        quit()

    os.mkdir("{0}/temp".format(directory))
    os.chdir("{0}/temp".format(directory))

    print("This may take a while.")

    if video is True:
        downloadcommand = [
            "youtube-dl", "--metadata-from-title", "%(artist)s - %(title)s",
            "-f", "bestvideo+bestaudio", "--add-metadata", "--output",
            "%(artist)s - %(title)s.%(ext)s", link
        ]
    else:
        downloadcommand = [
            "youtube-dl", "--metadata-from-title", "%(artist)s - %(title)s",
            "--extract-audio", "--audio-format", "mp3", "--audio-quality", "0",
            "--add-metadata", "--output", "%(artist)s - %(title)s.%(ext)s",
            link
        ]

    try:
        subprocess.check_output(downloadcommand, stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError:
        print(
            "Please check your URL, it shouldn't be a private playlist link (eg liked videos)"
        )
        quit()

    click.secho("File successfully downloaded.", fg="green", bold=True)
    types = ('*.mp3', '*.mp4', '*.mkv')
    list_of_files = []
    for files in types:
        list_of_files.extend(glob.glob(files))

    for file in list_of_files:
        print("File to send : {0}".format(file))
        with open(file, "rb") as song:
            file_data = pb.upload_file(song, file)
        to_device.push_file(**file_data)
        print("The file has been sent to your {0}.".format(to_device))

    if send:
        for i, device in enumerate(pb.chats, 1):
            print("{0} : {1}".format(i, device))
        index = int(
            rawinput(
                "Enter the corresponding chat no. for the person you want to send the file to. "
            ))
        try:
            chat = pb.chats[index - 1]
            for file in list_of_files:
                print("File to send : {0}".format(file))
                with open(file, "rb") as song:
                    file_data = pb.upload_file(song, file)
                pb.push_file(**file_data, chat=chat)
        except:
            print("Contact does not exist.")
        else:
            print("The file has been sent to ", chat)

    for file in list_of_files:
        if file.endswith((".mp3", "mp4", ".mkv")):
            os.rename("{0}/temp/{1}".format(directory, file),
                      "{0}/{1}".format(directory, file))

    os.rmdir("{0}/temp".format(directory))
    os.chdir(directory)

    if delete:
        for file in list_of_files:
            os.remove(file)
Exemple #26
0
class NotificationHandler:
    def __init__(self, pushBulletAPIKey, didReceiveCommand):
        # Setup pushBullet manager
        self.pushBulletAPIKey = pushBulletAPIKey
        self.didReceiveCommand = didReceiveCommand
        self.pushBulletManager = Pushbullet(self.pushBulletAPIKey)
        thread = Thread(target=self.__createListener)
        thread.start()
        # Setup Notification Queue
        self.__setupNotificationQueue()

    def __createListener(self):
        self.listener = Listener(account=self.pushBulletManager,
                                 on_push=self.on_push,
                                 http_proxy_host=HTTP_PROXY_HOST,
                                 http_proxy_port=HTTP_PROXY_PORT)
        self.listener.run_forever()

    def __setupNotificationQueue(self):
        print("setupNotificationQueue")
        self.notificationQueue = Queue(maxsize=QUEUE_MAX_SIZE)
        for i in range(NUM_THREAD):
            worker = Thread(target=self.__motionNotify, args=())
            worker.setDaemon(True)
            worker.start()

    def pushNotificationToMobile(self, filePath):
        self.notificationQueue.put(filePath)

    def pushToMobile(self, dataDictionary):
        print("pushToMobile: ", dataDictionary)
        self.notificationQueue.put(dataDictionary)

    def __motionNotify(self):
        print("__motionNotify called")
        while True:
            dataDictionary = self.notificationQueue.get()
            print("upload and notify: ", dataDictionary)
            if dataDictionary['type'] == "TEXT_MESSAGE":
                push = self.pushBulletManager.push_note(
                    dataDictionary['text'], '')
                print("push result: ", push)
            elif dataDictionary['type'] == "IMAGE_MESSAGE":
                filePath = dataDictionary['filePath']
                print("upload and push file: ", filePath)
                with open(filePath, "rb") as pic:
                    fileData = self.pushBulletManager.upload_file(
                        pic, dataDictionary['fileName'])
                    push = self.pushBulletManager.push_file(**fileData)
                    print("push result: ", push)
                    if "iden" in push:
                        os.remove(filePath)
            elif dataDictionary['type'] == "VIDEO_MESSAGE":
                push = self.pushBulletManager.push_note(
                    "The motion is out. Video uploading...", '')
                filePath = dataDictionary['filePath']
                print("upload and push file: ", filePath)
                with open(filePath, "rb") as pic:
                    fileData = self.pushBulletManager.upload_file(
                        pic, dataDictionary['fileName'])
                    push = self.pushBulletManager.push_file(**fileData)
                    print("push result: ", push)
                    if "iden" in push:
                        os.remove(filePath)
            else:
                print("Not support type: ", dataDictionary['Type'])
            self.notificationQueue.task_done()

    def __delete(self):
        self.listener.close()  # to stop the run_forever()

    def on_push(self, jsonMessage):
        if jsonMessage["type"] == "tickle" and jsonMessage["subtype"] == "push":
            allPushes = self.pushBulletManager.get_pushes()
            latest = allPushes[0]
            if 'body' in latest:
                body = latest['body']
                print(body)
                if body.startswith("@"):
                    self.didReceiveCommand(body)
        #		else:
        #			print("latest pushes: ", latest)
        #	else:
        #		print("latest pushes: ", latest)

    def notifyWithImage(self, filePath):
        with open(filePath, "rb") as pic:
            file_data = self.pushBulletManager.upload_file(pic, "picture.jpg")
            push = self.pushBulletManager.push_file(**file_data)

    def notifyWithVideo(self, filePath):
        with open(filePath, "rb") as pic:
            file_data = self.pushBulletManager.upload_file(pic, "video.h264")
            push = self.pushBulletManager.push_file(**file_data)
        os.remove("usps_cookies.pickle")
        #setup new session
        session = myusps.get_session(username, password, driver='firefox')
        #Download Image of mail
        image = session.get(item['image'], allow_redirects=False)
        if image.status_code == 200:
            with open("mailpieceImg.jpg", 'wb') as f:
                f.write(image.content)

        #upload to imgur
        imgurlink = client.upload_from_path("mailpieceImg.jpg",
                                            config=None,
                                            anon=True)
        print(imgurlink["link"])
        #Push to pushbullet if enabled
        if pushbullet_enabled == 1:
            push = pb.push_file(file_url=imgurlink["link"],
                                file_name="mailpieceImg.jpg",
                                file_type="image/jpeg")

        #construct slack message
        slack_data = {
            "attachments": [{
                "image_url": imgurlink["link"],
                "text": "",
            }]
        }

        #Write to Slack channel via MyUsps Application webhook
        slack_post(webhook_url, slack_data)
Exemple #28
0
	settings = json.load(f)
if settings['api_key'] == 'put_key_here':
	print('You should check the README on how to add your API key')
	exit(0)

try:
	pb = Pushbullet(settings['api_key'])
except:
	print ("Your API key is invalid")
	exit(1)

if settings['command_started_title'].isspace():
	if len(sys.argv) == 2:
		pb.push_note(settings['command_started_title'], 'Running command ' + sys.argv[1] + ' with no arguments')
	else:
		pb.push_note(settings['command_started_title'], 'Running command ' + sys.argv[1] + ' with arguments ' + str(sys.argv[2:]))

task_output = open('out.txt', 'w')
retcode = call(sys.argv[1:], stdout = task_output)
task_output.close()

with open('out.txt', 'rb') as f:
	filename = 'out_'+datetime.datetime.fromtimestamp(time.time()).strftime('%Y_%m_%d_%H%M%S')+'.txt'
	task_output_data = pb.upload_file(f, filename)
os.remove('out.txt')
	
if retcode == 0:
	pb.push_file(**task_output_data, title=settings['command_done_title'])
else:
	pb.push_file(**task_output_data, title=settings['command_error_title'], body='Command failed with errorcode:  ' + str(retcode) + '.  Output to follow')
Exemple #29
0
        logger.debug('Found HTML text: ' + html_text)
        body_text = '%s\n%s' % (body_text, html_text)

    # Handle images - Decode base64 and upload to pushbullet
    # If there are multiple images it will only do the first one
    if part.get_content_type() == 'image/jpg' and not is_file:
        is_file = True
        image_part = part.get_payload()
        file_name = datetime.now().strftime('%Y-%m-%d_%H-%M-%S') + '.jpg'
        file = io.BytesIO(image_part.decode('base64'))
        logger.debug('Uploading ' + file_name)
        file_data = pb.upload_file(file, file_name)


# Build the text
parse_part(msg)
sender = msg.get('From', 'Unknown')
body_text = '%s\nFrom: %s' % (body_text, sender)
body_text = body_text.strip()

# Send push
subject = msg.get('Subject', '(No subject)')
if is_file:
    logger.debug('Sending file push')
    push = pb.push_file(body=body_text, title=subject, **file_data)
else:
    logger.debug('Sending note push')
    push = pb.push_note(title=subject, body=body_text)

logger.info('Successfully pushed')
class RPiSurveillanceCamera:

    # Init class
    def __init__(self, configfile='config.json'):

        # Init config (load from JSON file)
        self.config = json.load(open(configfile))

        # Init camera
        self.camera = picamera.PiCamera()
        self.setupCamera()

        # Init GPIO pis
        self.initGPIO()

        # Init more stuff
        self.pushbullet = Pushbullet(self.config["pushbullet"]["accessToken"])
        self.outputDir = self.setOutputDirectory()

    # Setup camera
    def setupCamera(self):

        # Set resolution and framerate
        resolution = self.config["camera"]["resolution"]
        self.camera.resolution = (resolution["width"], resolution["height"])
        self.camera.framerate = self.config["camera"]["framerate"]

        # Set tags (Artist & Copyright) - in case of the images/videos getting online
        self.camera.exif_tags['IFD0.Artist'] = "{}".format(self.config["user"]["name"])
        self.camera.exif_tags['IFD0.Copyright'] = "© Copyright {} {}".format(
            time.strftime("%Y", time.localtime()),
            self.config["user"]["name"])

    # Init GPIO pins
    def initGPIO(self):

        # Set pin mode
        GPIO.setmode(GPIO.BCM)

        # Define GPIO pins
        ledSwitch = self.config["gpio"]["ledSwitch"]
        ledStatus = self.config["gpio"]["ledStatus"]
        sensorPin = self.config["gpio"]["sensor"]
        switchPin = self.config["gpio"]["switch"]

        # Set GPIO IN/OUT
        GPIO.setup(ledSwitch, GPIO.OUT)
        GPIO.setup(ledStatus, GPIO.OUT)
        GPIO.setup(sensorPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.setup(switchPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    # Set output directory path
    def setOutputDirectory(self):

        # Set output directory path from config
        outputDir = self.config["camera"]["outputDirectory"]

        # Create dir if necessary
        if not os.path.exists(outputDir):
            os.makedirs(outputDir)
            print("Created image folder: {}".format(outputDir))

        # Return directory path
        return outputDir

    # Taking a picture
    def makePicture(self):

        # Start camera preview
        self.camera.start_preview()

        # Set name for name (unique by time)
        fileName = 'picamera-shot-{}.jpg'.format(time.strftime("%y%m%d%H%M%S"))

        try:
            # Capture foto
            self.camera.capture(self.outputDir + fileName)

            # Log
            print("Picture: {}".format(self.outputDir + fileName))

        finally:
            # Close camera and return image path
            self.camera.close()
            return self.outputDir + fileName

    # Push image via Pushbullet
    def pushImage(self, image):

        # Open image
        with open(image, "rb") as pic:

            # Upload file to Pushbullet server
            file_data = self.pushbullet.upload_file(pic, "sample_iPod.m4v")

        # Push file
        self.pushbullet.push_file(**file_data)
Exemple #31
0
except:
    print("Your API key is invalid")
    exit(1)

if settings['command_started_title'].isspace():
    if len(sys.argv) == 2:
        pb.push_note(settings['command_started_title'],
                     'Running command ' + sys.argv[1] + ' with no arguments')
    else:
        pb.push_note(
            settings['command_started_title'], 'Running command ' +
            sys.argv[1] + ' with arguments ' + str(sys.argv[2:]))

task_output = open('out.txt', 'w')
retcode = call(sys.argv[1:], stdout=task_output)
task_output.close()

with open('out.txt', 'rb') as f:
    filename = 'out_' + datetime.datetime.fromtimestamp(
        time.time()).strftime('%Y_%m_%d_%H%M%S') + '.txt'
    task_output_data = pb.upload_file(f, filename)
os.remove('out.txt')

if retcode == 0:
    pb.push_file(**task_output_data, title=settings['command_done_title'])
else:
    pb.push_file(**task_output_data,
                 title=settings['command_error_title'],
                 body='Command failed with errorcode:  ' + str(retcode) +
                 '.  Output to follow')
Exemple #32
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4

from pushbullet import Pushbullet
import sys
import time
import ConfigParser
import subprocess

if __name__ == '__main__':
    config = ConfigParser.ConfigParser()
    config.read('chicken_door.cfg')
    api_key = config.get('pushbullet', 'api_key')
    pb = Pushbullet(api_key)

    try:
        cmd = "v4l2grab -d /dev/video0 -o /tmp/coop_door.jpg"
        subprocess.Popen(cmd,
                         shell=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
        time.sleep(1)
        with open("/tmp/coop_door.jpg", "rb") as pic:
            file_data = pb.upload_file(pic, "coop_door.jpg")
        push = pb.push_file(**file_data)

    except:
        print "BOOM:", sys.exc_info()
Exemple #33
0

def kill_motion():
    """Ensure the motion process is not active (blue webcam light off)."""
    if process_running('motion'):
        print('Stopping motion')
        return subprocess.check_output('sudo killall motion'.split()).decode('utf-8')


while (True):
    if (not is_erics_iphone_in_home_network()):
        ensure_motion_is_running()
        for jpg in glob.glob(os.path.join(motion_dir, '*.jpg')):
            # TODO: log instead
            with open(jpg, 'rb') as pic:
                # TODO: only push if cell phone not in house wifi
                file_data = pb.upload_file(pic, name(pic))
                push = pb.push_file(**file_data)
                # TODO: try-catch with logging
                os.remove(jpg)
                # Clean up motion_dir: discard swfs for room
        	for swf in glob.glob(os.path.join(motion_dir, '*.swf')):
                    os.remove(swf)
    else:
        kill_motion()
        for file in glob.glob(os.path.join(motion_dir, '*')):
            os.remove(file)
        # TODO: log instead
        print('Eric is home -- sleeping')
    time.sleep(30)