Пример #1
0
def serviceDel():
    uid = request.args.get('id', '')
    _service = Service()
    if _service.del_service(uid):
        return redirect('/services/')
    else:
        return '域名管理信息删除失败!'
Пример #2
0
 def test_models(self):
     #Create a Table and a Waiter
     table = Table(table_no="table1")
     db.session.add(table)
     table2 = Table(table_no="table2")
     db.session.add(table2)
     table3 = Table(table_no="table3")
     db.session.add(table3)
     table4 = Table(table_no="table4")
     db.session.add(table4)
     table5 = Table(table_no="table4")
     db.session.add(table4)
     waiter = Waiter(name="Juan")
     db.session.add(waiter)
     db.session.commit()
     service = Service(tip=90.80)
     db.session.add(service)
     db.session.commit()
     service = Service(tip=90.80)
     db.session.add(service)
     db.session.commit()
     service = Service(tip=90.80)
     db.session.add(service)
     db.session.commit()
     service = Service(tip=90.80)
     db.session.add(service)
     db.session.commit()
     try:
         service = Service(tip=90.80)
     except Exception:
         pass
Пример #3
0
def create_service_from_endpoint(endpoint,
                                 service_type,
                                 title=None,
                                 abstract=None):
    """
    Create a service from an endpoint if it does not already exists.
    """
    from models import Service
    if Service.objects.filter(url=endpoint).count() == 0:
        # check if endpoint is valid
        request = requests.get(endpoint)
        if request.status_code == 200:
            print 'Creating a %s service for endpoint %s' % (service_type,
                                                             endpoint)
            service = Service(type=service_type,
                              url=endpoint,
                              title=title,
                              abstract=abstract)
            service.save()
            return service
        else:
            print 'This endpoint is invalid, status code is %s' % request.status_code
    else:
        print 'A service for this endpoint %s already exists' % endpoint
        return None
Пример #4
0
    def search_service(self, pkg):
        """For HTTP, a service if not found by conventional method,
        the 'host' header can be used to determine destiny URL.

        The Service from 'host' header is searched the same way as a DNS cache answered.
        """

        service = super().search_service(pkg)

        if service:
            return service

        if hasattr(pkg.http, 'host'):
            # When header host is IP addr, create service 'Unknown (IP)'. 
            # If not, service will have name of the IP
            # The name must have info of the IP for the equals btw services
            if is_ipaddress(pkg.http.host):
                return Service.from_ip_only(pkg.http.host)
            else:
                name = get_significant_name_from_url(pkg.http.host)
                service = self.environment.service_analyzer.find_service_from_absolute_url(
                    pkg.http.host
                ) or self.environment.service_analyzer.find_service_from_url(
                    pkg.http.host) or Service.from_name(name)
                service.hosts.add(pkg.http.host)
                return service
        else:
            return None
Пример #5
0
def service_add(request, response_format='html'):
    "Service add"

    if not request.user.profile.is_admin('anaf.services'):
        return user_denied(
            request,
            message=
            "You don't have administrator access to the Service Support module"
        )

    if request.POST:
        if 'cancel' not in request.POST:
            service = Service()
            form = ServiceForm(request.user.profile,
                               request.POST,
                               instance=service)
            if form.is_valid():
                service = form.save()
                service.set_user_from_request(request)
                return HttpResponseRedirect(
                    reverse('services_service_view', args=[service.id]))
        else:
            return HttpResponseRedirect(reverse('services'))
    else:
        form = ServiceForm(request.user.profile)

    context = _get_default_context(request)
    context.update({'form': form})

    return render_to_response('services/service_add',
                              context,
                              context_instance=RequestContext(request),
                              response_format=response_format)
Пример #6
0
def populate_initial_services():
    """
    Populate a fresh installed Hypermap instances with basic services.
    """
    services_list = (
        ('Harvard WorldMap',
         'Harvard WorldMap open source web geospatial platform',
         'Hypermap:WorldMap', 'http://worldmap.harvard.edu'),
        ('NYPL MapWarper',
         'The New York Public Library (NYPL) MapWarper web site',
         'Hypermap:WARPER', 'http://maps.nypl.org/warper/maps'),
        ('Map Warper',
         'The MapWarper web site developed, hosted and maintained by Tim Waters',
         'Hypermap:WARPER', 'http://mapwarper.net/maps'),
        ('WorldMap Warp',
         'The MapWarper instance part of the Harvard WorldMap project',
         'Hypermap:WARPER', 'http://warp.worldmap.harvard.edu/maps'),
        ('WFP GeoNode', 'World Food Programme GeoNode', 'OGC:WMS',
         'http://geonode.wfp.org/geoserver/ows?'),
        ('NASA EARTHDATA', 'NASA EARTHDATA, powered by EOSDIS', 'OGC:WMTS',
         'http://map1.vis.earthdata.nasa.gov/wmts-geo/1.0.0/WMTSCapabilities.xml'
         ),
    )

    esri_endpoint = 'https://gis.ngdc.noaa.gov/arcgis/rest/services'
    print '*** Importing esri endpoint: %s' % esri_endpoint
    create_services_from_endpoint(esri_endpoint)

    for service in services_list:
        print '*** Importing %s' % service[0]
        service = Service(title=service[0],
                          abstract=service[1],
                          type=service[2],
                          url=service[3])
        service.save()
Пример #7
0
def create_service_from_endpoint(endpoint,
                                 service_type,
                                 title=None,
                                 abstract=None,
                                 catalog=None):
    """
    Create a service from an endpoint if it does not already exists.
    """
    from models import Service
    if Service.objects.filter(url=endpoint, catalog=catalog).count() == 0:
        # check if endpoint is valid
        request = requests.get(endpoint)
        if request.status_code == 200:
            LOGGER.debug('Creating a %s service for endpoint=%s catalog=%s' %
                         (service_type, endpoint, catalog))
            service = Service(type=service_type,
                              url=endpoint,
                              title=title,
                              abstract=abstract,
                              csw_type='service',
                              catalog=catalog)
            service.save()
            return service
        else:
            LOGGER.warning('This endpoint is invalid, status code is %s' %
                           request.status_code)
    else:
        LOGGER.warning(
            'A service for this endpoint %s in catalog %s already exists' %
            (endpoint, catalog))
        return None
Пример #8
0
def RegisterFile(Service=None, FileName=None, ProvisionedSpace="10G"):

    if Service  is None:
	raise StorageError('RegisterFile(): Service can not be None')

    if FileName is None:
	raise StorageError('RegisterFile(): FileName can not be None')

    vfilespace = StringSizeToBytes(ProvisionedSpace)
    
    if Service.freespace - vfilespace > 0:
	NewFile = File()
	NewFile.vfilename 	= FileName
        NewFile.ufid		= GetUniqueFileID(FileName)
	NewFile.pfilesize	= 0
        NewFile.vfilesize	= vfilespace
	NewFile.service		= Service
	NewFile.pfilename	= GetPhysicalFileName(Service.localpath, FileName)
	NewFile.status		= 'O'
	NewFile.save()
	
	SFreeSpace = CalculateFreeSpace(Service)
	Service.freespace = SFreeSpace
	Service.save()

	return NewFile
    else:
	raise StorageError('RegisterFile(): No have left space')
Пример #9
0
    def test_modify_entity(self):
        # TODO: test erroneous cases (required field deleted, field type
        # mismatch etc.)
        test_srv = Service.by_property(
            'name', u'Предоставление земельного участка многодетной семье')
        required_srv = Service.by_property(
            'name', u'Регистрация по месту жительства')
        kmplks_to_remove = Kompleks.by_property('name', u'Рождение ребенка')

        test_srv.prerequisite_description = u"это нужно будет удалить"
        test_srv.put()

        req_data = [
            {'name': 'short_description', 'value': u'тест тест тест'},
            {'name': "dependencies", 'edits': [
                {'values': [required_srv.urlsafe()], 'method': 'add'}]},
            {'name': 'related_komplekses', 'edits': [
                {'values': [kmplks_to_remove.urlsafe()],
                 'method': 'subtract'}]},
            {'name': 'prerequisite_description', 'value': None}]
        req_url = '/admin/api/entities/' + test_srv.urlsafe()

        response = self.testapp.put_json(req_url, req_data)
        self.assertEqual(response.status_int, 200)

        test_srv = from_urlsafe(test_srv.urlsafe())

        self.assertEqual(test_srv.prerequisite_description, None)
        self.assertNotIn(
            from_urlsafe(kmplks_to_remove.urlsafe(),key_only=True),
            test_srv.related_komplekses)
        self.assertIn(from_urlsafe(required_srv.urlsafe(), key_only=True),
                      test_srv.dependencies)
        self.assertEqual(test_srv.short_description, u'тест тест тест')
Пример #10
0
    def post(self, version):
        logging.debug("ServicesListHandler#post")

        if (self.valid_version(version)):
            
            name = self.request.get('name', default_value=None)
            description = self.request.get('description', default_value=None)
            serviceurl = self.request.get('serviceurl', default_value=None)
            pattern = self.request.get('pattern', default_value=None)
            freq = self.request.get('freq', default_value=None)
            
            if name and description:
                slug = slugify.slugify(name)
                existing_s = Service.get_by_slug(slug)

                # Update existing resource
                if existing_s:
                    existing_s.description = description
                    existing_s.serviceurl = serviceurl
                    existing_s.pattern = pattern
                    existing_s.freq = freq
                    existing_s.put()
                    self.json(existing_s.rest(self.base_url(version)))
                # Create new service
                else:
                    s = Service(name=name, slug=slug, description=description, serviceurl=serviceurl)
                    s.put()
                    self.json(s.rest(self.base_url(version)))
            else:
                self.error(400, "Bad Data: Name: %s, Description: %s" % (name, description))
        else:
            self.error(404, "API Version %s not supported" % version)
Пример #11
0
    def create_service(jwt):
        body = request.get_json()
        try:
            name = body.get('name', None)
            type = body.get('type', None)
            address = body.get('address', None)
            region_id = body.get('region_id', None)
            email = body.get('email', None)
            phone = body.get('phone', None)
            website = body.get('website', None)
            image = body.get('image', None)

            if (name is None) or (type is None) or (address is None) or (
                    region_id is None):
                abort(422)

            new_service = Service(name=name,
                                  type=type,
                                  address=address,
                                  region_id=region_id,
                                  email=email,
                                  phone=phone,
                                  website=website,
                                  image=image)
            new_service.insert()
            return jsonify({'success': True, 'created': new_service.id}), 200
        except BaseException:
            print(sys.exc_info())
            abort(422)
Пример #12
0
    def setUp(self):

        for s in range(0, SERVICE_NUMBER):
            service = Service(
                url='http://%s.fakeurl.com' % s,
                title='Title %s' % s,
                type='OGC_WMS',
            )
            service.save()
            for l in range(0, 20):
                layer = Layer(
                    name='Layer %s, from service %s' % (l, s),
                    bbox_x0=-179,
                    bbox_x1=179,
                    bbox_y0=-89,
                    bbox_y1=89,
                    service=service
                )
                layer.save()
                service.layer_set.add(layer)
        for c in range(0, TIMES_TO_CHECK):
            for s in range(0, SERVICE_NUMBER):
                service = Service.objects.all()[s]
                service.check()
                for layer in service.layer_set.all():
                    layer.check()
Пример #13
0
def import_services(service_list):
    """Add any services from file to django database"""
    current_services = read_current_services()
    for service in service_list:
        if service not in current_services:
            new_service = Service(service_name=service)
            new_service.save()
Пример #14
0
    def post(self, version, service_slug):
        logging.debug("ServiceInstanceHandler#post")
        name = self.request.get('name', default_value=None)
        description = self.request.get('description', default_value=None)
        region = self.request.get('region', default_value=None)
        
        if (self.valid_version(version)):
            service = Service.get_by_slug(service_slug)
            if service:
                if description:
                    service.description = description
                
                if name:
                    service.name = name

                if region:
                    service.region = Region.get_by_name(region)
                
                if name or description or region:
                    service.slug = Service.slugify(service.name, service.region.name)
                    service.put()
                    
                self.json(service.rest(self.base_url(version)))   
            else:
                self.error(404, "Service %s does not exist" % service_slug)
        else:
            self.error(404, "API Version %s not supported" % version)
Пример #15
0
    def post(self, version):
        if not self.valid_version(version):
            self.error(404, "API Version %s not supported" % version)
            return

        name = self.request.get('name', default_value=None)
        description = self.request.get('description', default_value=None)

        if not name or not description:
            self.error(400, "Bad Data: Name: %s, Description: %s" \
                           % (name, description))
            return

        slug = slugify.slugify(name)
        existing_s = Service.get_by_slug(slug)

        if existing_s:
            self.error(404, "A sevice with this name already exists")
            return

        s = Service(name=name, slug=slug, description=description)
        s.put()

        invalidate_cache()

        self.response.set_status(201)
        self.json(s.rest(self.base_url(version)))
Пример #16
0
 def test_get_reservations(self):
     customer = Customer(name='Teemu Teekkari',
                         email='teemu.teekkari@aalto fi')
     service1 = Service(name='service1',
                        price=10.0,
                        duration=60.0,
                        description='service1 description')
     service2 = Service(name='service1',
                        price=10.0,
                        duration=60.0,
                        description='service1 description')
     self.db.save(service1)
     self.db.save(service2)
     added_reservations = []
     date = QtCore.QDate.currentDate()
     resource = Resource(name="Resource1", resource_type="ROOM")
     for x in range(8, 19):
         start_time = QtCore.QTime(x, 0)
         end_time = QtCore.QTime(x, 59)
         start = QtCore.QDateTime(date, start_time)
         end = QtCore.QDateTime(date, end_time)
         new_reservation = Reservation(customer=customer,
                                       resource=resource,
                                       start=start,
                                       end=end,
                                       services=[service1, service2])
         self.db.save(new_reservation)
         added_reservations.append(new_reservation)
     reservations = self.db.get_reservations()
     for i in range(len(reservations)):
         self.assertEqual(reservations[i], added_reservations[i])
Пример #17
0
 def setUp(self):
     super(HistoryTest, self).setUp()
     Status.load_defaults()
     self.service = Service(slug="account",
                            name="Account",
                            description="The BEST SERVICE")
     self.service.put()
Пример #18
0
def service_add(request, response_format='html'):
    "Service add"

    if not request.user.profile.is_admin('anaf.services'):
        return user_denied(request,
                           message="You don't have administrator access to the Service Support module")

    if request.POST:
        if 'cancel' not in request.POST:
            service = Service()
            form = ServiceForm(
                request.user.profile, request.POST, instance=service)
            if form.is_valid():
                service = form.save()
                service.set_user_from_request(request)
                return HttpResponseRedirect(reverse('services_service_view', args=[service.id]))
        else:
            return HttpResponseRedirect(reverse('services'))
    else:
        form = ServiceForm(request.user.profile)

    context = _get_default_context(request)
    context.update({'form': form})

    return render_to_response('services/service_add', context,
                              context_instance=RequestContext(request), response_format=response_format)
Пример #19
0
def import_services(service_list):
    """Add any services from file to django database"""
    current_services = read_current_services()
    for service in service_list:
        if service not in current_services:
            new_service = Service(service_name=service)
            new_service.save()
Пример #20
0
def api_get_services(*, page='1'):
    page_index = get_page_index(page)
    num = yield from Service.findNumber('count(id)')
    p = Page(num, page_index)
    if num == 0:
        return dict(page=p, service=())
    service = yield from Service.findAll(limit=(p.offset, p.limit))
    return dict(page=p, service=service)
Пример #21
0
    def addservice_command(self, message=None):
        """Create a new service"""

        service_name = message.body.split(' ')[1]
        service = Service(key_name=service_name, name=service_name)
        service.put()

        message.reply("Added service %s" % service_name)
Пример #22
0
def api_get_services(*, page='1'):
    page_index = get_page_index(page)
    num = yield from Service.findNumber('count(id)')
    p = Page(num, page_index)
    if num == 0:
        return dict(page=p, service=())
    service = yield from Service.findAll(limit=(p.offset, p.limit))
    return dict(page=p, service=service)
Пример #23
0
class ServiceInstanceTest(StashboardTest):

    def setUp(self):
        super(ServiceInstanceTest, self).setUp()
        self.service = Service(name="Foo", slug="foo", description="foo")
        self.service.put()

    @patch("handlers.api.invalidate_cache")
    def test_delete_service(self, mock):
        response = self.delete("/admin/api/v1/services/foo")
        self.assertEquals(response.status_code, 200)

    def test_delete_wrong_service(self):
        response = self.delete("/admin/api/v1/services/bar")
        self.assertEquals(response.status_code, 404)

    def test_delete_wrong_version(self):
        response = self.delete("/admin/api/foo/services/foo")
        self.assertEquals(response.status_code, 404)

    def test_post_wrong_service(self):
        response = self.post("/admin/api/v1/services/bar")
        self.assertEquals(response.status_code, 404)

    def test_post_wrong_version(self):
        response = self.post("/admin/api/foo/services/foo")
        self.assertEquals(response.status_code, 404)

    def test_post_update_desc(self):
        response = self.post("/admin/api/v1/services/foo",
                data={"description": "hello"})
        self.assertEquals(response.headers["Content-Type"], "application/json")
        self.assertEquals(response.status_code, 200)

        service = Service.get(self.service.key())
        self.assertEquals(service.description, "hello")

    def test_post_update(self):
        response = self.post("/admin/api/v1/services/foo",
            data={"name": "bar"})
        self.assertEquals(response.headers["Content-Type"], "application/json")
        self.assertEquals(response.status_code, 200)

        service = Service.get(self.service.key())
        self.assertEquals(service.name, "bar")

    def test_get_wrong_service(self):
        response = self.get("/admin/api/v1/services/bar")
        self.assertEquals(response.status_code, 404)

    def test_get_wrong_version(self):
        response = self.get("/admin/api/foo/services/foo")
        self.assertEquals(response.status_code, 404)

    def test_get_service(self):
        response = self.get("/admin/api/v1/services/foo")
        self.assertEquals(response.status_code, 200)
        self.assertEquals(response.headers["Content-Type"], "application/json")
Пример #24
0
 def setUp(self):
     super(ServiceListInstanceTest, self).setUp()
     self.service_list = List(slug="foo", name="Foo", description="Bar")
     self.service_list.put()
     self.service = Service(list=self.service_list,
                            name="Foo",
                            slug="foo",
                            description="foo")
     self.service.put()
Пример #25
0
def service_create():
    name = request.form.get('name', '').strip()
    icon = request.form.get('icon', '').strip()
    if not name:
        return jsonify(Error.ARGUMENT_MISSING('name'))
    srv = Service(name, icon)
    db.session.add(srv)
    db.session.commit()
    return jsonify({"service": srv.as_dict(True)})
Пример #26
0
def service_create():
    name = request.form.get('name', '').strip()
    icon = request.form.get('icon', '').strip()
    if not name:
        return Error.ARGUMENT_MISSING('name')
    srv = Service(name, icon)
    db.session.add(srv)
    db.session.commit()
    return jsonify({"service": srv.as_dict(True)})
Пример #27
0
def populate_initial_services():
    """
    Populate a fresh installed Hypermap instances with basic services.
    """
    services_list = (
        (
            'Harvard WorldMap',
            'Harvard WorldMap open source web geospatial platform',
            'WM',
            'http://worldmap.harvard.edu'
        ),
        (
            'NYPL MapWarper',
            'The New York Public Library (NYPL) MapWarper web site',
            'WARPER',
            'http://maps.nypl.org/warper/maps'
        ),
        (
            'Map Warper',
            'The MapWarper web site developed, hosted and maintained by Tim Waters',
            'WARPER',
            'http://mapwarper.net/maps'
        ),
        (
            'WorldMap Warp',
            'The MapWarper instance part of the Harvard WorldMap project',
            'WARPER',
            'http://warp.worldmap.harvard.edu/maps'
        ),
        (
            'WFP GeoNode',
            'World Food Programme GeoNode',
            'OGC_WMS',
            'http://geonode.wfp.org/geoserver/ows?'
        ),
        (
            'NASA EARTHDATA',
            'NASA EARTHDATA, powered by EOSDIS',
            'OGC_WMTS',
            'http://map1.vis.earthdata.nasa.gov/wmts-geo/1.0.0/WMTSCapabilities.xml'
        ),
    )

    esri_endpoint = 'https://gis.ngdc.noaa.gov/arcgis/rest/services'
    print '*** Importing esri endpoint: %s' % esri_endpoint
    create_services_from_endpoint(esri_endpoint)

    for service in services_list:
        print '*** Importing %s' % service[0]
        service = Service(
            title=service[0],
            abstract=service[1],
            type=service[2],
            url=service[3]
        )
        service.save()
Пример #28
0
def update_service():
    params = request.args if request.method == 'GET' else request.form
    _id = params.get('id', '')
    _url = params.get('url', '')
    _username = params.get('username', '')
    _password = params.get('password', '')
    _func = params.get('func', '')
    _service = Service()
    _is_ok = _service.update_service(_url, _username, _password, _func, _id)
    return json.dumps({'is_ok': _is_ok})
Пример #29
0
def service_create():
    name = request.form.get('name', '').strip()
    icon = request.form.get('icon', '').strip()
    encrypted = request.form.get('encrypted',
                                 '').strip().lower() in ("1", "true", "yes")
    if not name:
        return jsonify(Error.ARGUMENT_MISSING('name'))
    srv = Service(name, icon, encrypted=encrypted)
    db.session.add(srv)
    db.session.commit()
    return jsonify({"service": srv.as_dict(True)})
Пример #30
0
    def test_create_event(self):
        s = Service(slug=u"hey", name=u"you", description=u"lol")
        s.put()

        stat = Status(name=u"you", slug=u"leave", description=u"why",
                      image=u"cry")
        stat.put()

        e = Event(status=stat, service=s, message=u"¨¥¨œ∑´æ")
        e.put()

        data = e.rest("/api")
Пример #31
0
    def setUp(self):
        self.group, created = Group.objects.get_or_create(name='test')
        self.user, created = DjangoUser.objects.get_or_create(
            username=self.username)
        self.user.set_password(self.password)
        self.user.save()
        perspective, created = Perspective.objects.get_or_create(
            name='default')
        perspective.set_default_user()
        perspective.save()

        ModuleSetting.set('default_perspective', perspective.id)

        self.contact_type = ContactType(name='test')
        self.contact_type.set_default_user()
        self.contact_type.save()

        self.contact = Contact(name='test', contact_type=self.contact_type)
        self.contact.set_default_user()
        self.contact.save()

        self.status = TicketStatus(name='TestStatus')
        self.status.set_default_user()
        self.status.save()

        self.queue = TicketQueue(name='TestQueue',
                                 default_ticket_status=self.status)
        self.queue.set_default_user()
        self.queue.save()

        self.ticket = Ticket(name='TestTicket',
                             status=self.status,
                             queue=self.queue)
        self.ticket.set_default_user()
        self.ticket.save()

        self.agent = ServiceAgent(related_user=self.user.profile,
                                  available_from=datetime.time(9),
                                  available_to=datetime.time(17))
        self.agent.set_default_user()
        self.agent.save()

        self.service = Service(name='test')
        self.service.set_default_user()
        self.service.save()

        self.sla = ServiceLevelAgreement(name='test',
                                         service=self.service,
                                         client=self.contact,
                                         provider=self.contact)
        self.sla.set_default_user()
        self.sla.save()
Пример #32
0
 def test_get_services(self):
     service1 = Service(name='service1',
                        price=10.0,
                        duration=60.0,
                        description='service1 description')
     service2 = Service(name='service1',
                        price=10.0,
                        duration=60.0,
                        description='service1 description')
     self.db.save(service1)
     self.db.save(service2)
     services = self.db.get_services()
     self.assertEqual(services, [service1, service2])
Пример #33
0
    def delete_service(jwt, service_id):

        service = Service.query.get(service_id)

        if service is None:
            print(sys.exc_info())
            abort(404)
        try:
            Service.delete(service)
            return jsonify({'success': True, 'deleted': service.id}), 200
        except BaseException:
            print(sys.exc_info())
            abort(422)
Пример #34
0
    def test_create_event(self):
        s = Service(slug=u"hey", name=u"you", description=u"lol")
        s.put()

        stat = Status(name=u"you",
                      slug=u"leave",
                      description=u"why",
                      image=u"cry")
        stat.put()

        e = Event(status=stat, service=s, message=u"¨¥¨œ∑´æ")
        e.put()

        data = e.rest("/api")
Пример #35
0
    def post(self):
        """Notify subscribers that a service changed status."""

        address = self.request.get('address')
        service = Service.get(self.request.get('service'))
        oldstatus = Status.get(self.request.get('oldstatus'))
        number = self.request.get('number')

        logging.info("Service: %s" % service)
        logging.info("Service name: %s" % service.name)

        msg = "%s changed state from %s to %s (%s)" % (
                service.name, oldstatus.name,
                service.current_event().status.name,
                service.current_event().message)

        user = Subscription.get_by_email(address)
        if user.status == "available" or not number:
        	status_code = xmpp.send_message(address, msg)
    		chat_message_sent = (status_code == xmpp.NO_ERROR)
		logging.info("Notified: %s\nmessage: %s code: %d" % (address, msg, status_code))
        elif user.status == "unavailable" and number:
		sms = smsgw(to = number, msg = msg)
		sms.send()
		logging.info("Offline SMS: %s\nmessage: %s" % (number, msg))
Пример #36
0
        def get_services():
            services = []
            for service in Service.query().filter(Service.list in lists).order(Service.name).fetch(100):
                event = yield service.current_event_async()
                if event is not None:
                    status = event.status
                else:
                    status = default_status

                if len(self.statuses) and not status.slug in self.statuses: continue

                today = datetime.today() + timedelta(days=1)
                current = yield service.history_async(1, default_status, start=today)
                
                current = current[0]

                has_issues = current["information"] and status.key == default_status.key

                history = yield service.history_async(5, default_status)

                service_dict = {
                    "slug": service.slug,
                    "name": service.name,
                    "url": service.url(),
                    "status": status,
                    "has_issues": has_issues,
                    "history": history,
                    }
                services.append(service_dict)

            raise ndb.Return(services)
Пример #37
0
def call_api(service, data):
    '''Submit service status to API'''
    service = Service.get_by_slug(service)
    status = Status.get_by_slug(data['status'])
    e = Event(service=service, status=status, message=data['message'])
    print json.dumps(data, sort_keys=True, skipkeys=True)
    e.put()
Пример #38
0
    def get(self, service_slug, year=None, month=None, day=None):
        service = Service.get_by_slug(service_slug)

        if not service:
            self.not_found()
            return

        try:
            if day:
                start_date = date(int(year),int(month),int(day))
                end_date = start_date + timedelta(days=1)
            elif month:
                start_date = date(int(year),int(month),1)
                days = calendar.monthrange(start_date.year, start_date.month)[1]
                end_date = start_date + timedelta(days=days)
            elif year:
                start_date = date(int(year),1,1)
                end_date = start_date + timedelta(days=365)
            else:
                start_date = None
                end_date = None
        except ValueError:
            self.not_found(404)
            return

        events = service.events

        if start_date and end_date:
            events.filter('start >= ', start_date).filter('start <', end_date)

        td = default_template_data()
        td["service"] = service
        td["events"] = events.order("-start").fetch(500)

        self.render(td, 'service.html')
def serverisdown (service):
	# Create a new event with the given status and given service
	service = Service.get_by_slug(service)
	status = Status.get_by_slug("down")        

	e = Event(service=service, status=status, message="The server could not be reached")
	e.put()
Пример #40
0
    def sub_command(self, message=None):
        """Subscribe the user to XMPP or SMS"""
        user = message.sender.split('/')[0]
	
        plist = message.body.split(' ' )
 	service_name = plist[1]

	if len(plist)>2:
	    type = "sms"
            user = plist[2]
	else:
	    type = "xmpp"
		
        service = Service.all().filter('name = ', service_name).get()

        if service:
            subscription = Subscription.all().filter('address =', user).filter('service = ', service).get()
            if subscription:
                message.reply("user %s is already subscribed to service %s" % (user, service.name))
            else:
                subscription = Subscription(key_name=hashlib.sha1(user).hexdigest(), type=type, address=user, service=service)
                subscription.put()
                message.reply("Subscribed %s to service %s" % (user, service.name))
        else:
            message.reply("Sorry, I couldn't find a service called "
                          "%s" % service_name)
Пример #41
0
    def post(self, version, service_slug):
        logging.debug("ServiceInstanceHandler#post")
        name = self.request.get('name', default_value=None)
        description = self.request.get('description', default_value=None)
        serviceurl = self.request.get('serviceurl', default_value=None)
        pattern = self.request.get('pattern', default_value=None)
        freq = self.request.get('freq', default_value=None)
        
        if (self.valid_version(version)):
            service = Service.get_by_slug(service_slug)
            if service:
                if description:
                    service.description = description
                
                if name:
                    service.name = name
                    
                if serviceurl:
                    service.serviceurl = serviceurl
                
                if pattern:
                    service.pattern = pattern

                if freq:
                    service.freq = int(freq)
                
                if name or description or serviceurl or pattern or freq:
                    service.put()
                    
                self.json(service.rest(self.base_url(version)))   
            else:
                self.error(404, "Service %s does not exist" % service_slug)
        else:
            self.error(404, "API Version %s not supported" % version)
Пример #42
0
 def setUp(self):
     super(ServiceListInstanceTest, self).setUp()
     self.service_list = List(slug="foo", name="Foo", description="Bar")
     self.service_list.put()
     self.service = Service(list=self.service_list, name="Foo", slug="foo",
                            description="foo")
     self.service.put()
Пример #43
0
    def unsub_command(self, message=None):
        """Unsubscribe the user from a service"""
        user = message.sender.split('/')[0]

        plist = message.body.split(' ' )
        service_name = plist[1]

	if len(plist)>2:
	    type = "sms"
            user = plist[2]
	else:
	    type = "xmpp"
		
        service = Service.all().filter('name = ', service_name).get()

        if service:
            subscription = Subscription.all().filter('address =', user).filter('service = ', service).filter('type =', type).get()
            if subscription:
                subscription.delete()
		if type == "xmpp":
	            	mobile = Mobile.all().filter('subscription = ', subscription).get()
			if mobile:
				mobile.delete()
                message.reply("Unsubscribed %s from service %s" % (user, service.name))
            else:
                message.reply("user %s is not subscribed to service %s" % (user, service.name))
        else:
            message.reply("Sorry, I couldn't find a service called "
                          "%s" % service_name)
Пример #44
0
    def data(self):
        services = []
        default_status = Status.get_default()

        query = Service.all().filter("list =", self.list).order("name")

        for service in query.fetch(100):
            event = service.current_event()
            if event is not None:
                status = event.status
            else:
                status = default_status

            today = date.today() + timedelta(days=1)
            current, = service.history(1, default_status, start=today)
            has_issues = (current["information"] and
                          status.key() == default_status.key())

            service_dict = {
                "slug": service.slug,
                "name": service.name,
                "url": service.url(),
                "status": status,
                "has_issues": has_issues,
                "history": service.history(5, default_status),
                }
            services.append(service_dict)

        return {
            "days": get_past_days(5),
            "statuses": Status.all().fetch(100),
            "services": services,
            }
  def get(self):

    role = self.session.get('role')
    user_session = self.session.get("user")

    if role != "admin" and role != "staff":
      self.redirect("/users/login?message={0}".format("You are not authorized to view this page"))
      return

    if not self.legacy:
      self.redirect("/#/admin/programs/new")

    form = Service.NewServiceForm()
    template_values = {
      "form": form,
      "user_session": user_session
    }
    language = None
    if "language" in self.request.cookies:
      language = self.request.cookies["language"]
    else:
      language = "fr"
      self.response.set_cookie("language", "fr")

    language = language.replace('"', '').replace("'", "")
    if language == "fr":

      LEGACY_TEMPLATE = JINJA_ENVIRONMENT.get_template('fr_new_services.html')
    else:
      LEGACY_TEMPLATE = JINJA_ENVIRONMENT.get_template('new_services.html')
    self.response.write(LEGACY_TEMPLATE.render(template_values))
Пример #46
0
    def post(self, version, service_slug):
        logging.debug("ServiceInstanceHandler#post")
        name = self.request.get('name', default_value=None)
        description = self.request.get('description', default_value=None)
        serviceurl = self.request.get('serviceurl', default_value=None)
        pattern = self.request.get('pattern', default_value=None)
        freq = self.request.get('freq', default_value=None)

        if (self.valid_version(version)):
            service = Service.get_by_slug(service_slug)
            if service:
                if description:
                    service.description = description

                if name:
                    service.name = name

                if serviceurl:
                    service.serviceurl = serviceurl

                if pattern:
                    service.pattern = pattern

                if freq:
                    service.freq = int(freq)

                if name or description or serviceurl or pattern or freq:
                    service.put()

                self.json(service.rest(self.base_url(version)))
            else:
                self.error(404, "Service %s does not exist" % service_slug)
        else:
            self.error(404, "API Version %s not supported" % version)
Пример #47
0
    def sms_command(self, message=None):
        """Subscribe the user to a offline SMS"""

        plist = message.body.split(' ')
	if len(plist)==3:
	        user = message.sender.split('/')[0]
	 	service_name = plist[1]
	 	number = plist[2]
	
	        service = Service.all().filter('name = ', service_name).get()
	
	        if service:
		 	subscription = Subscription.all().filter('address =', user).filter('service = ', service).get()
		
		        if subscription:
		            mobile = Mobile.all().filter('number =', number).get()
		            if mobile:
		                message.reply("user %s is already registered backup mobile %s for service %s" % (user, mobile.number,service_name))
		            else:
		                mobile = Mobile(number=number, subscription = subscription)
		                mobile.put()
		                message.reply("Subscribed user %s to backup mobile %s for service %s" % (user, number,service_name))
		        else:
		            message.reply("Sorry, I couldn't find a subscription on %s for %s" % (service_name,user))
	        else:
	            message.reply("Sorry, I couldn't find a service called "
	                          "%s" % service_name)
	else:
		message.reply("Usage: sms SERVICE +61412345678")
Пример #48
0
    def data(self):
        services = []
        dstatus = Status.default()

        for s in Service.all().order("name").fetch(100):
            event = s.current_event()
            if event is not None:
                status = event.status
            else:
                status = dstatus

            service = {
                "slug": s.slug,
                "name": s.name,
                "url": s.url(),
                "status": status,
                "history": s.history(5, dstatus)
                }
            services.append(service)

        return {
            "days": get_past_days(5),
            "statuses": Status.all().fetch(100),
            "services": services,
            }
Пример #49
0
    def unsms_command(self, message=None):
        """Unsubscribe the user from a service"""
	plist = message.body.split(' ')
	if len(plist)==2:
	        user = message.sender.split('/')[0]
	
	        service_name = plist[1]
	
	        service = Service.all().filter('name = ', service_name).get()
	
	        if service:
		    subscription = Subscription.all().filter('address =', user).filter('service = ', service).get()
		
		    if subscription:
	            	mobile = Mobile.all().filter('subscription = ', subscription).get()
	            	if mobile:
		    	    message.reply("Unsubscribed user %s from backup mobile %s for service %s" % (user, mobile.number,service_name))
	            	    mobile.delete()
			else:
			    message.reply("No backup mobile for user %s on %s service" % (user,service_name))
	 	    else:
	            	message.reply("User %s is not subscribed to service %s" % (user, service.name))
	        else:
	            message.reply("Sorry, I couldn't find a service called "
                          "%s" % service_name)
	else:
		 message.reply("Usege: unsms SERVICE +6112345678")
def serverisup (service):
	# Create a new event with the given status and given service
	service = Service.get_by_slug(service)
	status = Status.get_by_slug("up")        

	e = Event(service=service, status=status, message="The server is responding.")
	e.put()
Пример #51
0
    def delete(self, version, service_slug, sid):
        if not self.valid_version(version):
            self.error(404, "API Version %s not supported" % version)
            return

        service = Service.get_by_slug(service_slug)

        if not service:
            self.error(404, "Service %s not found" % service_slug)
            return

        try:
            event = Event.get(db.Key(sid))
        except datastore_errors.BadKeyError:
            self.error(404, "Event %s not found" % sid)
            return

        if not event or service.key() != event.service.key():
            self.error(404, "No event for Service %s with sid = %s" \
                           % (service_slug, sid))
            return

        event.delete()
        invalidate_cache()

        # Why not JSON?
        self.success(event.rest(self.base_url(version)))
Пример #52
0
def service_add_post():
    from flask import request
    messages = session["messages"]
    user_id = messages[messages.index(":")+1:len(messages)-1]
    user = User.query.filter_by(id=user_id).first()
    name = user.first_name + " " + user.last_name
    title = request.form["title"]
    price = float(request.form["price"])
    desc = request.form["desc"]
    category = request.form["category"]
    address = request.form["address"]
    file = request.files["file"]
    requested_by = user_id
    request = int(request.form["request_service"])
    try:
        id_num = Service.query.all()[-1].id + 1
    except:
        id_num = 0
    ext_index = file.filename.rfind(".")
    ext = file.filename[ext_index:]
    filename = str(str(id_num) + ext).upper()
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    s = Service(title, price, desc, category, address, requested_by, request, filename)
    db_session.add(s)
    db_session.commit()
    return redirect("/home/All")
Пример #53
0
    def delete(self, version, service_slug, sid):
        if not self.valid_version(version):
            self.error(404, "API Version %s not supported" % version)
            return

        service = Service.get_by_slug(service_slug)

        if not service:
            self.error(404, "Service %s not found" % service_slug)
            return

 
        try:
            event = Event.get(db.Key(sid))
        except datastore_errors.BadKeyError:
            self.error(404, "Event %s not found" % sid)
            return

        if not event or service.key() != event.service.key():
            self.error(404, "No event for Service %s with sid = %s" \
                           % (service_slug, sid))
            return

        event.delete()
        invalidate_cache()

        # Why not JSON?
        self.success(event.rest(self.base_url(version)))
Пример #54
0
    def search_service(self, pkg):
        """This method will return a Service that is involved with that pkg.
        
        Priority to search:
            1) From destiny IP. For example 50.22.198.206 -> WhatsApp
            2) From URL (because of previous DNS query)
                2.1) Absolute URL match with DB
                2.2) URL relative match with DB (fb.com matches with xxx.ssss.dddd.fff.fb.com)
                2.3) Name from URL

        """
        service = self.environment.service_analyzer.find_service_from_ip(
            pkg.ip.dst)
        if service:
            service.ips.add(pkg.ip.dst)
            return service
        else:
            host = self.environment.find_host(pkg.ip.dst)
            if host:
                name = get_significant_name_from_url(host)
                ret_service = self.environment.service_analyzer.find_service_from_absolute_url(
                    host
                ) or self.environment.service_analyzer.find_service_from_url(
                    host) or Service.from_name(name)

                ret_service.hosts.add(host)
                return ret_service
            else:
                return None
Пример #55
0
    def insert(username):
        """New Service"""
        form = ServiceForm(obj=request.json, prefix="service")
        form.category_ids.choices = CategoryHandler.list_for_select()

        if form.validate():
            name = form.name.data
            description = form.description.data
            is_active = form.is_active.data

            category_ids = form.category_ids.data

            service = Service(
                username=username,
                name=name,
                description=description,
                is_active=is_active,
                updated=datetime.datetime.now(),
                created=datetime.datetime.now()
            )

            db.session.add(service)

            try:
                db.session.commit()

            except:
                db.session.rollback()
                # return error message
                return {"error": "Error when adding an service"}

            # append the categories
            if len(category_ids) > 0:
                service.set_categoiry_ids(category_ids)

                try:
                    db.session.commit()
                except:
                    db.session.rollback()

            ServiceHandler.upload(service, form)

            # success, return new item
            return {"item": service.serialize()}

        # return form errors
        return {"errors": form.errors}
Пример #56
0
    def on_post(self,request,response):
        # Get raw data from request body
        try:
            raw_data = request.stream.read()
        except Exception as ex:
            raise falcon.HTTPBadRequest(ex.message)
        
        # Jsonify the raw data
        try:
            data = json.loads(raw_data,encoding='utf-8')
        except ValueError:
            raise falcon.HTTPError(falcon.HTTP_400,'Unrecognized JSON','Unable to decode request body')

        # Return 404 if <tenant> does not exist
        if not data['tenant']:
            response.status = falcon.HTTP_404
            return

        # Return 404 if <integration_type> does not exist
        if not data['integration_type']:
            response.status = falcon.HTTP_404
            return

        # Validate data
        emptyValueKey = common.isEmpty(data['configuration'])
        if emptyValueKey:
            raise falcon.HTTPBadRequest('{} is missing'.format(emptyValueKey))
            return

        emptyValueKey = common.isEmpty(data['configuration']['wsdl_urls'])
        if emptyValueKey:
            raise falcon.HTTPBadRequest('{} is missing'.format(emptyValueKey))
            return

        # Query data from database
        result = Service.objects(tenant__iexact=data['tenant'], integration_type__iexact=data['integration_type']).exclude('id')
        
        ## No record found - insert new record. Else, update the existing record
        if result.count() < 1:
            new_config = Service(**data)
            new_config.save()
        else:
            result.modify(upsert=True, new=True, set__configuration=data['configuration'])

        # Response
        response.status = falcon.HTTP_200
        response.body = result.to_json()