예제 #1
0
def test_upload_file_request_fails(requests, pb_refresh):
    first_response = Mock()
    first_response.status_code = 400
    first_response.json.return_value = {
        "data": "upload_data",
        "file_url": "imageurl",
        "upload_url": "http://uploadhere.google.com",
    }

    second_response = Mock()
    second_response.status_code = 200

    session = Mock()
    session.post.return_value = first_response

    requests.post.return_value = second_response
    requests.codes.ok = 200

    pb = PushBullet("apikey")
    pb._session = session

    with open("tests/test.png", "rb") as test_file:

        with pytest.raises(PushbulletError):
            pb.upload_file(test_file, "test.png", "image/png")

    requests.post.assert_not_called()
class PushBulletAlert:
	def __init__(self, api_key, imagedir):
		self.pb = PushBullet(api_key)
		self.imagedir = imagedir

	def sendAlert(self, image):
		imagedata = open(os.path.join(self.imagedir, image), 'rb')
		success, file_data = self.pb.upload_file(imagedata, 'Motion detected: ' + image)
		success, push = self.pb.push_file(**file_data)
		return success 
class PushBulletAlert:
    def __init__(self, api_key, imagedir):
        self.pb = PushBullet(api_key)
        self.imagedir = imagedir

    def sendAlert(self, image):
        imagedata = open(os.path.join(self.imagedir, image), 'rb')
        success, file_data = self.pb.upload_file(imagedata,
                                                 'Motion detected: ' + image)
        success, push = self.pb.push_file(**file_data)
        return success
def pushSelfie(message):
	try:
		p = PushBullet(apiKey)
		myPhone = p.devices[0]
		print("uploading")
		with open('/home/pi/sb/selfie.jpg', "rb") as pic:
			file_data = p.upload_file(pic,"selfie.jpg")
		file_data = str(file_data)
		fileURL = file_data[file_data.find("https"):file_data.find("'})")]
		print (fileURL)
		myPhone.push_file(file_url=fileURL,file_name="selfie.jpg",file_type="image/jpeg")
	except: #todo: gracefully handle exceptions, wouldya
                e = sys.exc_info()[0]
                print(e)
예제 #5
0
def take_photo_and_push(pushbullet_auth_key, pushbullet_device_names):
    """ Takes a photo and sends to the cloud via PushBullet.
        Implements pushbullet.py, see https://pypi.python.org/pypi/pushbullet.py
        Implements picamera.py, see http://raspberrypi.org/picamera-pure-python-interface-for-camera-module
    """
    file_name = datetime.datetime.now().strftime("%I:%M%p %m-%d-%Y") + '.jpg'
    file_path = os.path.join('/home/pi', file_name)
    with picamera.PiCamera() as camera:
        camera.vflip = True
        camera.hflip = True
        camera.resolution = (1024, 768)
        camera.capture(file_path)

    pb = PushBullet(pushbullet_auth_key)

    with open(file_path, 'rb') as pic:
        message = 'SmartDoor ' + re.sub('.png', "", file_name)
        success, file_data = pb.upload_file(
            pic,
            message,
            'image/jpeg',
        )

    upload_message = "{0} uploading picture {1} to url {2}".format(
        'Success' if str(success) else 'Failure', file_data.get('file_name'),
        file_data.get('file_url'))
    print(upload_message)
    devices = pb.devices

    if any(
        [item in pushbullet_device_names for item in pushbullet_device_names]):
        for deviceName in pushbullet_device_names:
            device_list = [
                d for d in devices if d.nickname == deviceName and d.active
            ]
            device = device_list[0] if device_list else None
            if device is not None:
                success, push = device.push_file(**file_data)
                print('Successfully pushed ' + push.get('iden') + ' to ' +
                      device.nickname)
    else:
        success, push = pb.push_file(**file_data)
        print('Successfully pushed ' + push.get('iden') + ' to all devices')

    os.remove(file_path)
예제 #6
0
def test_upload_file(requests, pb_refresh):
    first_response = Mock()
    first_response.status_code = 200
    first_response.json.return_value = {
        "data": "upload_data",
        "file_url": "imageurl",
        "upload_url": "http://uploadhere.google.com",
    }

    second_response = Mock()
    second_response.status_code = 200

    session = Mock()
    session.post.return_value = first_response

    requests.post.return_value = second_response
    requests.codes.ok = 200

    pb = PushBullet("apikey")
    pb._session = session

    with open("tests/test.png", "rb") as test_file:
        response = pb.upload_file(test_file, "test.png")

        assert response == {
            "file_type": "image/png",
            "file_url": "imageurl",
            "file_name": "test.png",
        }

        session.post.assert_called_once_with(
            pb.UPLOAD_REQUEST_URL,
            data=json.dumps({
                "file_name": "test.png",
                "file_type": "image/png"
            }),
        )

        requests.post.assert_called_once_with(
            "http://uploadhere.google.com",
            data="upload_data",
            files={"file": test_file},
        )
예제 #7
0
def take_photo_and_push(pushbullet_auth_key, pushbullet_device_names):
    """ Takes a photo and sends to the cloud via PushBullet.
        Implements pushbullet.py, see https://pypi.python.org/pypi/pushbullet.py
        Implements picamera.py, see http://raspberrypi.org/picamera-pure-python-interface-for-camera-module
    """
    file_name = datetime.datetime.now().strftime("%I:%M%p %m-%d-%Y") + '.jpg'
    file_path = os.path.join('/home/pi', file_name)
    with picamera.PiCamera() as camera:
        camera.vflip = True
        camera.hflip = True
        camera.resolution = (1024, 768)
        camera.capture(file_path)

    pb = PushBullet(pushbullet_auth_key)

    with open(file_path, 'rb') as pic:
        message = 'SmartDoor ' + re.sub('.png', "", file_name)
        success, file_data = pb.upload_file(pic, message, 'image/jpeg',)

    upload_message = "{0} uploading picture {1} to url {2}".format(
        'Success' if str(success) else 'Failure',
        file_data.get('file_name'),
        file_data.get('file_url'))
    print(upload_message)
    devices = pb.devices

    if any([item in pushbullet_device_names for item in pushbullet_device_names]):
        for deviceName in pushbullet_device_names:
            device_list = [d for d in devices if d.nickname == deviceName and d.active]
            device = device_list[0] if device_list else None
            if device is not None:
                success, push = device.push_file(**file_data)
                print('Successfully pushed ' + push.get('iden') + ' to ' + device.nickname)
    else:
        success, push = pb.push_file(**file_data)
        print('Successfully pushed ' + push.get('iden') + ' to all devices')

    os.remove(file_path)
#!/usr/python

from pushbullet import PushBullet
from subprocess import call
import time

pb = PushBullet('KEY_HERE')
while True:
	call(["streamer","-f", "jpeg", "-o","image.jpeg"])
	with open("image.jpeg", "rb") as pic:
   		success, file_data = pb.upload_file(pic, "picture.jpg")

	success, push = pb.push_file(**file_data)
	time.sleep(600)

예제 #9
0
from pushbullet import PushBullet

api_key = "q3U8S546S0D8tHJb8PrCzHaKABoHbnZy"

pb = PushBullet(api_key)
with open("gem1.png", "rb") as pic:
    file_data = pb.upload_file(pic, "gem1.png")

push = pb.push_file(**file_data)
예제 #10
0

def getFileName():
    return '/home/pi/program/picture/' + datetime.datetime.now().strftime(
        '%Y-%m-%d%H:%M:%S') + '.png'


while True:
    input_state = GPIO.input(21)
    if input_state == True:
        GPIO.output(10, 1)
        GPIO.output(led_green, 0)
        GPIO.output(led_red, 1)
        print('Motion Detected')
        push = devices.push_note("Alert!!", "Intruder Alert!")
        timeCaptured = getFileName()
        camera.rotation = -90
        camera.capture(timeCaptured)
        print("Image Captured")
        print("Uploading...")
        GPIO.output(10, 0)
        with open(timeCaptured, "rb") as pic:
            file_data = p.upload_file(pic, "alert.jpg")
        push = p.push_file(**file_data)
    else:
        print('SAFE!')
        GPIO.output(10, 0)
        GPIO.output(led_red, 0)
        GPIO.output(led_green, 1)
        time.sleep(2)
예제 #11
0
from pushbullet import PushBullet

pb = PushBullet('YOUR API_TOKEN')
import datetime


def take_picture(path_):
    import pygame.camera

    pygame.camera.init()
    cam = pygame.camera.Camera(pygame.camera.list_cameras()[0])
    cam.start()
    img = cam.get_image()
    pygame.image.save(img, path_)
    pygame.camera.quit()


time = datetime.datetime.now()
import os
acc = os.getlogin()

phone = pb.devices[0]
take_picture('C:\\Users\\' + acc + '\\Desktop\\photo.bmp')

with open('C:\\Users\\' + acc + '\\Desktop\\photo.bmp', "rb") as pic:
    file_data = pb.upload_file(pic, "picture.jpg")

pb.push_note("Log in to account " + acc + " at " + str(time), "", device=phone)

push = pb.push_file(**file_data)
예제 #12
0
class MainWindow(QMainWindow):
    connected = pyqtSignal(bool)

    def __init__(self, app):
        QMainWindow.__init__(self)
        self.app = app
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self._exit = False
        self.ui.action_Exit.triggered.connect(self.exit)
        self.ui.actionAbout_Qt.triggered.connect(app.aboutQt)
        self.setWindowIcon(QIcon(':/icons/logo32'))
        self.listener = None
        self.tray = None
        self.pusher = None
        self._connected = False

        self.settings_dlg = SettingsDlg(self)
        self.settings_dlg.saved.connect(self.reconnect)

        self.tray = PushbulletTray(self)
        self.connect_actions()
        self.connect_pushbullet()

        self.tray.show()

    def connect_actions(self):
        self.ui.action_Settings.triggered.connect(self.settings_dlg.show)
        self.ui.browseFileBtn.clicked.connect(self.choice_file)
        self.ui.action_Refresh.triggered.connect(self.refresh)
        # List Items
        self.ui.addItemBtn.clicked.connect(self.add_item_list)
        self.ui.removeItemBtn.clicked.connect(self.remove_item_list)
        self.ui.clearItemsBtn.clicked.connect(self.clear_item_list)
        self.ui.itemsList.itemDoubleClicked.connect(self.edit_item_list)

    @pyqtSlot()
    def add_item_list(self):
        item = QListWidgetItem("item", self.ui.itemsList)
        item.setFlags(item.flags() | Qt.ItemIsEditable)
        self.ui.itemsList.addItem(item)

    @pyqtSlot()
    def remove_item_list(self):
        if self.ui.itemsList.currentRow() >= 0:
            self.ui.itemsList.takeItem(self.ui.itemsList.currentRow())

    @pyqtSlot()
    def clear_item_list(self):
        self.ui.itemsList.clear()

    @pyqtSlot(QListWidgetItem)
    def edit_item_list(self, item):
        self.ui.itemsList.editItem(item)

    @pyqtSlot()
    def choice_file(self):
        file_to_send = QFileDialog.getOpenFileName(self, "choose file to send")
        if file_to_send and not file_to_send.isEmpty():
            self.ui.filePathEdt.setText(file_to_send)

    @pyqtSlot()
    def refresh(self):
        self.refresh_devices()

    @pyqtSlot()
    def refresh_devices(self):
        self.ui.devicesList.clear()
        for device in self.pusher.devices:
            device_item = QListWidgetItem(device.nickname)
            device_item.setData(Qt.UserRole, device)
            self.ui.devicesList.addItem(device_item)

    def connect_pushbullet(self):
        if config.value('key') is not None and not config.value('key').toString().isEmpty():
            proxy_host = str(config.value('proxy.host').toString())
            proxy_port, int_conv_ok = config.value('proxy.port').toInt()
            if proxy_host.strip() == '':
                proxy_host = proxy_port = None
            self.pusher = PushBullet(str(config.value('key').toString()))
            self.listener = QPushBulletListener(self, self.pusher, proxy_host, proxy_port)
            self.listener.start()
            self.connect_systray()
            self.connect_pushes_actions()
            self.refresh_devices()
            self.connected.emit(True)
            self._connected = True
        else:
            self.connected.emit(False)

    def disconnect_pushbullet(self):
        self.connected.emit(False)
        if False and self.listener is not None:
            print "systray"
            self.disconnect_systray()
            print "listener quit"
            self.listener.quit()
            print "listener terminate"
            self.listener.terminate()
            print "disconnect_pushes"
            self.disconnect_pushes_actions()
            self.listener = None


    @pyqtSlot()
    def push_note(self):
        if self.pusher and len(self.ui.devicesList.selectedItems()) == 1:
            device = self.ui.devicesList.selectedItems()[0].data(Qt.UserRole).toPyObject()
            device.push_note(str(self.ui.noteTitleEdt.text()), str(self.ui.noteTextEdt.toPlainText()))
        else:
            QMessageBox.warning(self, "Cannot push", "There is no target device selected")

    @pyqtSlot()
    def push_link(self):
        if self.pusher and len(self.ui.devicesList.selectedItems()) == 1:
            device = self.ui.devicesList.selectedItems()[0].data(Qt.UserRole).toPyObject()
            device.push_link(str(self.ui.linkTitleEdt.text()), str(self.ui.linkUrlEdt.text()))
        else:
            QMessageBox.warning(self, "Cannot push", "There is no target device selected")

    @pyqtSlot()
    def push_list(self):
        if self.pusher and len(self.ui.devicesList.selectedItems()) == 1:
            device = self.ui.devicesList.selectedItems()[0].data(Qt.UserRole).toPyObject()
            widget_items = [self.ui.itemsList.item(n) for n in range(0, self.ui.itemsList.count())]
            items = map(lambda x: str(x.text()), widget_items)
            device.push_list(str(self.ui.listTitleEdt.text()), items)
        else:
            QMessageBox.warning(self, "Cannot push", "There is no target device selected")

    @pyqtSlot()
    def push_file(self):
        if self.pusher and len(self.ui.devicesList.selectedItems()) == 1:
            device = self.ui.devicesList.selectedItems()[0].data(Qt.UserRole).toPyObject()
            fname = str(self.ui.filePathEdt.text())
            with open(fname, "rb") as f_to_send:
                success, file_data = self.pusher.upload_file(f_to_send, os.path.basename(fname))
                if success:
                    device.push_file(**file_data)
        else:
            QMessageBox.warning(self, "Cannot push", "There is no target device selected")

    @pyqtSlot()
    def push_address(self):
        if self.pusher and len(self.ui.devicesList.selectedItems()) == 1:
            device = self.ui.devicesList.selectedItems()[0].data(Qt.UserRole).toPyObject()
            device.push_address(str(self.ui.addressTitleEdt.text()), str(self.ui.addressTxt.toPlainText()))
        else:
            QMessageBox.warning(self, "Cannot push", "There is no target device selected")

    def connect_pushes_actions(self):
        self.ui.sendNoteBtn.clicked.connect(self.push_note)
        self.ui.sendLinkBtn.clicked.connect(self.push_link)
        self.ui.sendFileBtn.clicked.connect(self.push_file)
        self.ui.sendListBtn.clicked.connect(self.push_list)
        self.ui.sendAddressBtn.clicked.connect(self.push_address)

    def disconnect_pushes_actions(self):
        self.ui.sendNoteBtn.clicked.disconnect(self.push_note)
        self.ui.sendLinkBtn.clicked.disconnect(self.push_link)
        self.ui.sendFileBtn.clicked.disconnect(self.push_file)
        self.ui.sendListBtn.clicked.disconnect(self.push_list)
        self.ui.sendAddressBtn.clicked.disconnect(self.push_address)

    def connect_systray(self, ):
        if self.tray is not None:
            self.connected.connect(self.tray.connected)
            self.listener.on_link.connect(self.tray.on_link)
            self.listener.on_note.connect(self.tray.on_note)
            self.connected.emit(self._connected)

    def disconnect_systray(self):
        if self.tray is not None:
            self.listener.on_link.disconnect(self.tray.on_link)
            self.listener.on_note.disconnect(self.tray.on_note)

    @pyqtSlot()
    def reconnect(self):
        if self.listener is not None:
            self.disconnect_pushbullet()
        self.connect_pushbullet()

    @pyqtSlot()
    def exit(self):
        self._exit = True
        self.close()

    def closeEvent(self, event):
        if not self._exit:
            self.hide()
            event.ignore()
        else:
            QMainWindow.closeEvent(self, event)