How to hide swagger models at bottom with gin-swagger? - api

I am using gin-swagger for generating API document.
It shows Models at the bottom of the page list by default.
How to hide it?

I met the same issue before, I removed one annotation in comment and Models gone. But I could not remember the name of annotation, however, you can compare your annotaions with below and remove the additional one.
// #Summary Get all users
// #Description Get all users
// #Tags UserMgt
// #Accept json
// #Produce json
// #Param filter body object{UserFilter} true "filter"
// #Success 200 {array} object{models.User} "users"
// #Failure 400 {object} object{models.User} "users not found"
// #Router /user/all [post]
// #Security ApiKeyAuth
func GetAllUsers(ctx *gin.Context) {
....omitted....
}

You juste have to add this line
ginSwagger.DefaultModelsExpandDepth(-1))
like that
ginSwagger.WrapHandler(swaggerFiles.Handler,
ginSwagger.DefaultModelsExpandDepth(-1))

Related

Autodesk PDF Extension - Preventing page in query string override

I'm currently looking to implement pagination within the ForgeViewer PDF Extenstion, in the documentation there's a note that 'page' in the querystring will override any value passed to load model. I wondered if this was configurable or we were able to prevent this.
// URL parameter page will override value passed to loadModel
viewer.loadModel(‘path/to/file.pdf’, { page: 1 });
This is causing us a few issues as we use 'page' for other purposes and we'll have to rework quite a bit to rename our current page querystring which we're using for paginating tables.
That's correct. If you look inside the PDF extension's code (https://developer.api.autodesk.com/modelderivative/v2/viewers/7.*/extensions/PDF/PDF.js) then you'll find that this behaviour is hardcoded unfortunately 😞
I can think of two workarounds:
a) Use a URL param other than page - e.g. sheet?
b) Overwrite the current URL so that the page number will become what you need
// Original URL is: http://127.0.0.1:5500/index.html?page=2
// we change it to page=1
// This should change the URL content without a reload
history.pushState('', '', 'index.html?page=1');
viewer.loadModel("AutoCAD_Sample_Part1.pdf", {}, (model) => {
You could also achieve the same like this:
viewer.loadExtension('Autodesk.PDF').then(function(ext) {
// Original URL is: http://127.0.0.1:5500/index.html?page=2
// we change it to page=1
viewer.loadModel("AutoCAD_Sample_Part1.pdf", {}, (model) => {
ext.hyperlinkTracker.changePage(1)

Custom 404 template file in Drupal 8

How can I create a custom 404 page in Drupal 8?
I have created a new page(Content) in the backoffice called 404 (node number 100).
I have set it as the 404 default page at Configuration >
Basic site settings.
It works with the content that I have set in the Backoffice.
But now I want it to be editable programatically and I don't know how can I create the overriding file.
I have tried to create mytheme/templates/html--node--100.html.twig and it works only when the request its directly that url (node/100), but it doesn't work when you try a random slug on the URL and drupal has to resolve it. When this happens, drupal is serving me the content that the 404 page has in the backoffice and not in the file that I have just created.
I have tried several files like page--404-html.twig, html--node--404.html.twig, html--page--404.html.twig,... but it doesn't work neither
Can anyone lend me a hand?
page--system--404.html.twig (or the equivalent for other 4xx statuses) no longer works in Drupal 8.3 as the 4xx response handling has changed. You'll now need the core patch from https://www.drupal.org/node/2363987 or a similar custom module hook that adds template suggestions for these pages:
/**
* Implements hook_theme_suggestions_page() to set 40x template suggestions
*/
function MYMODULE_theme_suggestions_page(array $variables) {
$path_args = explode('/', trim(\Drupal::service('path.current')->getPath(), '/'));
$suggestions = theme_get_suggestions($path_args, 'page');
$http_error_suggestions = [
'system.401' => 'page__401',
'system.403' => 'page__403',
'system.404' => 'page__404',
];
$route_name = \Drupal::routeMatch()->getRouteName();
if (isset($http_error_suggestions[$route_name])) {
$suggestions[] = $http_error_suggestions[$route_name];
}
return $suggestions;
}
EDIT: It's probably nicer to use hook_theme_suggestions_page_alter to modify the suggestions array. See an updated version of this code in https://www.drupal.org/project/fourxx_templates (or https://github.com/ahebrank/fourxx_templates/blob/8.x-1.x/fourxx_templates.module)
The following implementation adds a template suggestion for page, in this case if you create a page--404.html.twig file in your theme, you'll be able to customize the page and works with Drupal 8.5.1
MYTHEME.theme
/**
* Implements hook_theme_suggestions_HOOK_alter().
*/
function MYTHEME_theme_suggestions_page_alter(&$suggestions, $variables, $hook) {
/**
* 404 template suggestion.
*/
if (!is_null(Drupal::requestStack()->getCurrentRequest()->attributes->get('exception'))) {
$status_code = Drupal::requestStack()->getCurrentRequest()->attributes->get('exception')->getStatusCode();
switch ($status_code) {
case 404: {
$suggestions[] = 'page__' . (string) $status_code;
break;
}
default:
break;
}
}
}
and create a template called page--404.html.twig and override with your stuff.
OR,
if you want to add suggestions for all error pages, just take out the switch statement.
/**
* Implements hook_theme_suggestions_HOOK_alter().
*/
function MYTHEME_theme_suggestions_page_alter(&$suggestions, $variables) {
/**
* error page template suggestions.
*/
if (!is_null(Drupal::requestStack()->getCurrentRequest()->attributes->get('exception'))) {
$status_code = Drupal::requestStack()->getCurrentRequest()->attributes->get('exception')->getStatusCode();
$suggestions[] = 'page__' . (string) $status_code;
}
}
You can now use page--404.html.twig. Just be sure you don't set a node as the 404 page. Source: https://www.drupal.org/node/2960810
Try page--system--404.html.twig

Get current page request url in handlebars?

Is there a way to the current request url or path in Handlebars? I need to be able to switch what parts of the theme is loaded based on paths. I've tried {{url}} ... no luck. Using latest Stencil with Cornerstone.
I had to do something like this for a project with 3 different category page layouts. Without custom category templates in Stencil, you have to get a little creative.
First, inject the handlebars URL into your category.js file using the BigCommerce's inject handlebar helper seen here. Then parse it so you get only the unique parts, then perform some logic based on what you want to do.
I used the breadcrumb li length as an indicator of how deep I was in the category tree. There is likely a better way, but this is what I thought of first, and it worked just fine.
category.html
{{inject "currentPage" category.url}}
category.js
var pageURL = this.context.currentPage;
var pageURL = pageURL.replace(/\//g," ").replace("http:","").replace("storeurl.mybigcommerce.com","").replace("storeurl.com","").trim();
var catName = pageURL.substr(0,pageURL.indexOf(' '));
console.log('pageURL = ' + pageURL);
console.log('catName = ' + catName);
console.log($('ul.breadcrumbs li').length);
if( $('ul.breadcrumbs li').length == 3 ){
if(catName == "black-decker"){
if($(".cat-img").length){
$(".page").addClass("model-list");
$(".cat-img").hide();
$(".page").append("<div class='model-wrap'><div class='model-catalog' data-reveal-id='myModal'><span class='click-larger'>Click to view larger</span></div></div>");
$(".sidebarBlock-heading").text("Select Your Model Number Below:");
$(".brand-img").each(function(){
$(this).addClass(catName);
});
} else {
$(".page").addClass("model-list");
$(".sidebarBlock-heading").text("Select Your Model Number Below:");
$(".brand-img").each(function(){
$(this).addClass(catName);
});
// make page full width
$(".page-sidebar.cf.Left").addClass("full-width");
}
}
// MORE CODE etc...

EmberJS Route to 'single' getting JSONP

I'm having trouble with EmberJS to create a single view to posts based on the ID, but not the ID of the array, I actually have a ID that comes with the json I got from Tumblr API.
So the ID is something like '54930292'.
Next I try to use this ID to do another jsonp to get the post for this id, it works if you open the api and put the id, and actually if you open the single url with the ID on it, works too, the problem is:
When, on the front page for example, I click on a link to go to the single, it returns me nothing and raise a error.
But if you refresh the page you get the content.
Don't know how to fix and appreciate some help :(
I put online the code: http://tkrp.net/tumblr_test/
The error you were getting was because the SingleRoute was being generated as an ArrayController but the json response was not an Array.
App.SingleController = Ember.ObjectController.extend({
});
Further note that the model hook is not fired when using linkTo and other helpers. This because Ember assumes that if you linked to a model, the model is assumed to be as specified, and it directly calls setupController with that model. In your case, you need to still load the individual post. I added the setupController to the route to do this.
App.SingleRoute = Ember.Route.extend({
model: function(params) {
return App.TKRPTumblr.find(params.id);
},
setupController: function(controller, id) {
App.TKRPTumblr.find(id)
.then(function(data) {
controller.set('content', data.response);
});
}
});
I changed the single post template a bit to reflect how the json response. One final change I made was to directly return the $.ajax. Ember understands jQuery promises directly, so you don't need to do any parsing.
Here is the updated jsbin.
I modified: http://jsbin.com/okezum/6/edit
Did this to "fix" the refresh single page error:
setupController: function(controller, id) {
if(typeof id === 'object'){
controller.set('content', id.response);
}else{
App.TKRPTumblr.find(id)
.then(function(data) {
controller.set('content', data.response);
});
}
}
modified the setupController, since I was getting a object when refreshing the page and a number when clicking the linkTo
Dont know if it's the best way to do that :s

Instagram API: How to get all user media?

In general I need to get all user media.
User has more than 250 photos.
I do /users/1/media/recent/?access_token=...&count=250
But it returns only 20 photos.
Maybe instagram has a limit for getting media.
If it is, response has a pagination to solve it.
But there are only max ID photo. How to know the first (min) ID photo to paginate it then?
You're right, the Instagram API will only return 20 images per call. So you'll have to use the pagination feature.
If you're trying to use the API console. You'll want to first allow the API console to authenticate via your Instagram login. To do this you'll want to select OAUTH2 under the Authentication dropdown.
Once Authenticated, use the left hand side menu to select the users/{user-id}/media/recent endpoint. So for the sake of this post for {user-id} you can just replace it with self. This will then use your account to retrieve information.
At a bare minimum that is what's needed to do a GET for this endpoint. Once you send, you'll get some json returned to you. At the very top of the returned information after all the server info, you'll see a pagination portion with next_url and next_max_id.
next_max_id is what you'll use as a parameter for your query. Remember max_id is the id of the image that is the oldest of the 20 that was first returned. This will be used to return images earlier than this image.
You don't have to use the max_id if you don't want to. You can actually just grab the id of the image where you'd like to start querying more images from.
So from the returned data, copy the max_id into the parameter max_id. The request URL should look something like this https://api.instagram.com/v1/users/self/media/recent?max_id=XXXXXXXXXXX where XXXXXXXXXXX is the max_id. Hit send again and you should get the next 20 photos.
From there you'll also receive an updated max_id. You can then use that again to get the next set of 20 photos until eventually going through all of the user's photos.
What I've done in the project I'm working on is to load the first 20 photos returned from the initial recent media request. I then, assign the images with a data-id (-id can actually be whatever you'd like it to be). Then added a load more button on the bottom of the photo set.
When the button is clicked, I use jQuery to grab the last image and it's data-id attribute and use that to create a get call via ajax and append the results to the end of the photos already on the page. Instead of a button you could just replace it to have a infinite scrolling effect.
Hope that helps.
I've solved this issue with the optional parameter count set to -1.
It was a problem in Instagram Developer Console. max_id and min_id doesn't work there.
See http://instagram.com/developer/endpoints/ for information on pagination. You need to subsequentially step through the result pages, each time requesting the next part with the next_url that the result specifies in the pagination object.
In June 2016 Instagram made most of the functionality of their API available only to applications that have passed a review process. They still however provide JSON data through the web interface, and you can add the parameter __a=1 to a URL to only include the JSON data.
max=
while :;do
c=$(curl -s "https://www.instagram.com/username/?__a=1&max_id=$max")
jq -r '.user.media.nodes[]?|.display_src'<<<"$c"
max=$(jq -r .user.media.page_info.end_cursor<<<"$c")
jq -e .user.media.page_info.has_next_page<<<"$c">/dev/null||break
done
Edit: As mentioned in the comment by alnorth29, the max_id parameter is now ignored. Instagram also changed the format of the response, and you need to perform additional requests to get the full-size URLs of images in the new-style posts with multiple images per post. You can now do something like this to list the full-size URLs of images on the first page of results:
c=$(curl -s "https://www.instagram.com/username/?__a=1")
jq -r '.graphql.user.edge_owner_to_timeline_media.edges[]?|.node|select(.__typename!="GraphSidecar").display_url'<<<"$c"
jq -r '.graphql.user.edge_owner_to_timeline_media.edges[]?|.node|select(.__typename=="GraphSidecar")|.shortcode'<<<"$c"|while read l;do
curl -s "https://www.instagram.com/p/$l?__a=1"|jq -r '.graphql.shortcode_media|.edge_sidecar_to_children.edges[]?.node|.display_url'
done
To make a list of the shortcodes of each post made by the user whose profile is opened in the frontmost tab in Safari, I use a script like this:
sjs(){ osascript -e'{on run{a}','tell app"safari"to do javascript a in document 1',end} -- "$1";}
while :;do
sjs 'o="";a=document.querySelectorAll(".v1Nh3 a");for(i=0;e=a[i];i++){o+=e.href+"\n"};o'>>/tmp/a
sjs 'window.scrollBy(0,window.innerHeight)'
sleep 1
done
What I had to do is (in Javascript) is go through all pages by using a recursive function. It's dangerouse as instagram users could have thousands of pictures i a part from that (so your have to controle it) I use this code: (count parameter I think , doesn't do much)
instagramLoadDashboard = function(hash)
{
code = hash.split('=')[1];
$('#instagram-pictures .images-list .container').html('').addClass('loading');
ts = Math.round((new Date()).getTime() / 1000);
url = 'https://api.instagram.com/v1/users/self/media/recent?count=200&min_timestamp=0&max_timestamp='+ts+'&access_token='+code;
instagramLoadMediaPage(url, function(){
galleryHTML = instagramLoadGallery(instagramData);
//console.log(galleryHTML);
$('#instagram-pictures .images-list .container').html(galleryHTML).removeClass('loading');
initImages('#instagram-pictures');
IGStatus = 'loaded';
});
};
instagramLoadMediaPage = function (url, callback)
{
$.ajax({
url : url,
dataType : 'jsonp',
cache : false,
success: function(response){
console.log(response);
if(response.code == '400')
{
alert(response.error_message);
return false;
}
if(response.pagination.next_url !== undefined) {
instagramData = instagramData.concat(response.data);
return instagramLoadMediaPage(response.pagination.next_url,callback);
}
instagramData = instagramData.concat(response.data);
callback.apply();
}
});
};
instagramLoadGallery = function(images)
{
galleryHTML ='<ul>';
for(var i=0;i<images.length;i++)
{
galleryHTML += '<li><img src="'+images[i].images.thumbnail.url+'" width="120" id="instagram-'+images[i].id+' data-type="instagram" data-source="'+images[i].images.standard_resolution.url+'" class="image"/></li>';
}
galleryHTML +='</ul>';
return galleryHTML;
};
There some stuff related to print out a gallery of picture.
Use the best recursion function for getting all posts of users.
<?php
set_time_limit(0);
function getPost($url,$i)
{
static $posts=array();
$json=file_get_contents($url);
$data = json_decode($json);
$ins_links=array();
$page=$data->pagination;
$pagearray=json_decode(json_encode($page),true);
$pagecount=count($pagearray);
foreach( $data->data as $user_data )
{
$posts[$i++]=$user_data->link;
}
if($pagecount>0)
return getPost($page->next_url,$i);
else
return $posts;
}
$posts=getPost("https://api.instagram.com/v1/users/CLIENT-ACCOUNT-NUMBER/media/recent?client_id=CLIENT-ID&count=33",0);
print_r($posts);
?>
You can user pagination of Instagram PHP API: https://github.com/cosenary/Instagram-PHP-API/wiki/Using-Pagination
Something like that:
$Instagram = new MetzWeb\Instagram\Instagram(array(
"apiKey" => IG_APP_KEY,
"apiSecret" => IG_APP_SECRET,
"apiCallback" => IG_APP_CALLBACK
));
$Instagram->setSignedHeader(true);
$pictures = $Instagram->getUserMedia(123);
do {
foreach ($pictures->data as $picture_data):
echo '<img src="'.$picture_data->images->low_resolution->url.'">';
endforeach;
} while ($pictures = $instagram->pagination($pictures));
Use the next_url object to get the next 20 images.
In the JSON response there is an pagination array:
"pagination":{
"next_max_tag_id":"1411892342253728",
"deprecation_warning":"next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead",
"next_max_id":"1411892342253728",
"next_min_id":"1414849145899763",
"min_tag_id":"1414849145899763",
"next_url":"https:\/\/api.instagram.com\/v1\/tags\/lemonbarclub\/media\/recent?client_id=xxxxxxxxxxxxxxxxxx\u0026max_tag_id=1411892342253728"
}
This is the information on specific API call and the object next_url shows the URL to get the next 20 pictures so just take that URL and call it for the next 20 pictures.
For more information about the Instagram API check out this blogpost: Getting Friendly With Instagram’s API
Instagram developer console has provided the solution for it. https://www.instagram.com/developer/endpoints/
To use this in PHP, here is the code snippet,
/**
**
** Add this code snippet after your first curl call
** assume the response of the first call is stored in $userdata
** $access_token have your access token
*/
$maximumNumberOfPost = 33; // it can be 20, depends on your instagram application
$no_of_images = 50 // Enter the number of images you want
if ($no_of_images > $maximumNumberOfPost) {
$ImageArray = [];
$next_url = $userdata->pagination->next_url;
while ($no_of_images > $maximumNumberOfPost) {
$originalNumbersOfImage = $no_of_images;
$no_of_images = $no_of_images - $maximumNumberOfPost;
$next_url = str_replace("count=" . $originalNumbersOfImage, "count=" . $no_of_images, $next_url);
$chRepeat = curl_init();
curl_setopt_array($chRepeat, [
CURLOPT_URL => $next_url,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer $access_token"
],
CURLOPT_RETURNTRANSFER => true
]);
$userRepeatdata = curl_exec($chRepeat);
curl_close($chRepeat);
if ($userRepeatdata) {
$userRepeatdata = json_decode($userRepeatdata);
$next_url = $userRepeatdata->pagination->next_url;
if (isset($userRepeatdata->data) && $userRepeatdata->data) {
$ImageArray = $userRepeatdata->data;
}
}
}
}