CCMain.m 247 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641
  1. //
  2. // CCMain.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotos.h"
  26. #import "CCSynchronize.h"
  27. #import "CCTransfersCell.h"
  28. #import "OCActivity.h"
  29. #import "OCNotifications.h"
  30. #import "OCNotificationsAction.h"
  31. #import "OCFrameworkConstants.h"
  32. #import "OCCapabilities.h"
  33. #import "CTAssetCheckmark.h"
  34. #import "NCAutoUpload.h"
  35. #import "NCBridgeSwift.h"
  36. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate, UITextViewDelegate, createFormUploadAssetsDelegate, MGSwipeTableCellDelegate, CCLoginDelegate, CCLoginDelegateWeb>
  37. {
  38. tableMetadata *_metadata;
  39. BOOL _isRoot;
  40. BOOL _isViewDidLoad;
  41. BOOL _isOfflineServerUrl;
  42. BOOL _isPickerCriptate; // if is cryptated image or video back from picker
  43. BOOL _isSelectedMode;
  44. NSMutableDictionary *_selectedFileIDsMetadatas;
  45. NSUInteger _numSelectedFileIDsMetadatas;
  46. NSMutableArray *_queueSelector;
  47. NSMutableDictionary *_statusSwipeCell;
  48. UIImageView *_ImageTitleHomeCryptoCloud;
  49. UIView *_reMenuBackgroundView;
  50. UITapGestureRecognizer *_singleFingerTap;
  51. NSString *_directoryGroupBy;
  52. NSString *_directoryOrder;
  53. NSUInteger _failedAttempts;
  54. NSDate *_lockUntilDate;
  55. NSString *_fatherPermission;
  56. UIRefreshControl *_refreshControl;
  57. UIDocumentInteractionController *_docController;
  58. CCHud *_hud;
  59. CCHud *_hudDeterminate;
  60. // Datasource
  61. CCSectionDataSourceMetadata *_sectionDataSource;
  62. NSDate *_dateReadDataSource;
  63. // Search
  64. BOOL _isSearchMode;
  65. NSString *_searchFileName;
  66. NSMutableArray *_searchResultMetadatas;
  67. NSString *_depth;
  68. NSString *_noFilesSearchTitle;
  69. NSString *_noFilesSearchDescription;
  70. NSTimer *_timerWaitInput;
  71. // Login
  72. CCLoginWeb *_loginWeb;
  73. CCLogin *_loginVC;
  74. BOOL _loadingFolder;
  75. }
  76. @end
  77. @implementation CCMain
  78. #pragma --------------------------------------------------------------------------------------------
  79. #pragma mark ===== Init =====
  80. #pragma --------------------------------------------------------------------------------------------
  81. - (id)initWithCoder:(NSCoder *)aDecoder
  82. {
  83. if (self = [super initWithCoder:aDecoder]) {
  84. _directoryOrder = [CCUtility getOrderSettings];
  85. _directoryGroupBy = [CCUtility getGroupBySettings];
  86. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  87. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  88. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  89. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  90. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  91. }
  92. return self;
  93. }
  94. #pragma --------------------------------------------------------------------------------------------
  95. #pragma mark ===== View =====
  96. #pragma --------------------------------------------------------------------------------------------
  97. - (void)viewDidLoad
  98. {
  99. [super viewDidLoad];
  100. // init object
  101. _metadata = [tableMetadata new];
  102. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  103. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  104. _selectedFileIDsMetadatas = [NSMutableDictionary new];
  105. _statusSwipeCell = [NSMutableDictionary new];
  106. _queueSelector = [NSMutableArray new];
  107. _isViewDidLoad = YES;
  108. _fatherPermission = @"";
  109. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  110. _searchResultMetadatas = [NSMutableArray new];
  111. _searchFileName = @"";
  112. _depth = @"infinity";
  113. _noFilesSearchTitle = @"";
  114. _noFilesSearchDescription = @"";
  115. // delegate
  116. self.tableView.delegate = self;
  117. self.tableView.tableFooterView = [UIView new];
  118. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  119. self.tableView.emptyDataSetDelegate = self;
  120. self.tableView.emptyDataSetSource = self;
  121. self.searchController.delegate = self;
  122. self.searchController.searchBar.delegate = self;
  123. [[CCNetworking sharedNetworking] settingDelegate:self];
  124. // Custom Cell
  125. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  126. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  127. // long press recognizer TableView
  128. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  129. [self.tableView addGestureRecognizer:longPressRecognizer];
  130. // Pull-to-Refresh
  131. [self createRefreshControl];
  132. // Register for 3D Touch Previewing if available
  133. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  134. {
  135. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  136. }
  137. // Back Button
  138. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  139. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"] style:UIBarButtonItemStylePlain target:nil action:nil];
  140. // reMenu Background
  141. _reMenuBackgroundView = [[UIView alloc] init];
  142. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  143. // if this is not Main (the Main uses inizializeMain)
  144. if (_isRoot == NO && app.activeAccount.length > 0) {
  145. // Settings this folder & delegate & Loading datasource
  146. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  147. // Load Datasource
  148. [self reloadDatasource:_serverUrl];
  149. // Read (File) Folder
  150. [self readFileReloadFolder];
  151. }
  152. // Title
  153. [self setTitle];
  154. // Search
  155. self.definesPresentationContext = YES;
  156. self.searchController.searchResultsUpdater = self;
  157. self.searchController.dimsBackgroundDuringPresentation = NO;
  158. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].seperator;
  159. [self.searchController.searchBar sizeToFit];
  160. self.searchController.searchBar.delegate = self;
  161. // Hide Search Filed on Load
  162. self.tableView.tableHeaderView = self.searchController.searchBar;
  163. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  164. }
  165. // Apparirà
  166. - (void)viewWillAppear:(BOOL)animated
  167. {
  168. [super viewWillAppear:animated];
  169. // test
  170. if (app.activeAccount.length == 0)
  171. return;
  172. // Settings this folder & delegate & Loading datasource
  173. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  174. [[CCNetworking sharedNetworking] settingDelegate:self];
  175. // Color
  176. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  177. [app aspectTabBar:self.tabBarController.tabBar hidden:NO];
  178. if (_isSelectedMode)
  179. [self setUINavigationBarSelected];
  180. else
  181. [self setUINavigationBarDefault];
  182. // If not editing mode remove _selectedFileIDs
  183. if (!self.tableView.editing)
  184. [_selectedFileIDsMetadatas removeAllObjects];
  185. // Plus Button
  186. [app plusButtonVisibile:true];
  187. }
  188. // E' arrivato
  189. - (void)viewDidAppear:(BOOL)animated
  190. {
  191. [super viewDidAppear:animated];
  192. // Active Main
  193. app.activeMain = self;
  194. // Test viewDidLoad
  195. if (_isViewDidLoad) {
  196. _isViewDidLoad = NO;
  197. } else {
  198. if (app.activeAccount.length > 0 && [_selectedFileIDsMetadatas count] == 0) {
  199. // Load Datasource
  200. [self reloadDatasource:_serverUrl];
  201. // Read (file) Folder
  202. [self readFileReloadFolder];
  203. }
  204. }
  205. // Title
  206. [self setTitle];
  207. }
  208. - (void)viewWillDisappear:(BOOL)animated
  209. {
  210. [super viewWillDisappear:animated];
  211. [self closeAllMenu];
  212. }
  213. - (void)didReceiveMemoryWarning
  214. {
  215. [super didReceiveMemoryWarning];
  216. // Dispose of any resources that can be recreated.
  217. }
  218. - (BOOL)prefersStatusBarHidden
  219. {
  220. return NO;
  221. }
  222. // detect scroll for remove keyboard in search mode
  223. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  224. {
  225. if (_isSearchMode && scrollView == self.tableView) {
  226. [self.searchController.searchBar endEditing:YES];
  227. }
  228. }
  229. - (void)changeTheming
  230. {
  231. if (self.isViewLoaded && self.view.window)
  232. [app changeTheming:self];
  233. // Refresh control
  234. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  235. // Reload Table View
  236. [self tableViewReloadData];
  237. }
  238. #pragma --------------------------------------------------------------------------------------------
  239. #pragma mark ===== Initizlize Mail =====
  240. #pragma --------------------------------------------------------------------------------------------
  241. - (void)initializeMain:(NSNotification *)notification
  242. {
  243. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  244. _directoryGroupBy = nil;
  245. _directoryOrder = nil;
  246. _dateReadDataSource = nil;
  247. // test
  248. if (app.activeAccount.length == 0)
  249. return;
  250. if ([app.listMainVC count] == 0 || _isRoot) {
  251. // This is Root home main add list
  252. appDelegate.homeMain = self;
  253. _isRoot = YES;
  254. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  255. appDelegate.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  256. [appDelegate.listMainVC setObject:self forKey:_serverUrl];
  257. // go Home
  258. [self.navigationController popToRootViewControllerAnimated:NO];
  259. // Crypto Mode
  260. if ([[CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]] length] == 0) {
  261. appDelegate.isCryptoCloudMode = NO;
  262. } else {
  263. appDelegate.isCryptoCloudMode = YES;
  264. }
  265. _isFolderEncrypted = NO;
  266. // setting Networking
  267. [[CCNetworking sharedNetworking] settingDelegate:self];
  268. [[CCNetworking sharedNetworking] settingAccount];
  269. // Remove search mode
  270. [self cancelSearchBar];
  271. // populate shared Link & User
  272. NSArray *results = [[NCManageDatabase sharedInstance] getShares];
  273. if (results) {
  274. appDelegate.sharesLink = results[0];
  275. appDelegate.sharesUserAndGroup = results[1];
  276. }
  277. // Load Datasource
  278. [self reloadDatasource:_serverUrl];
  279. // Read (File) Folder
  280. [self readFileReloadFolder];
  281. // Setting Theming
  282. [app settingThemingColorBrand];
  283. // Load photo datasorce
  284. if (appDelegate.activePhotos)
  285. [appDelegate.activePhotos reloadDatasourceForced];
  286. // remove all of detail
  287. if (appDelegate.activeDetail)
  288. [appDelegate.activeDetail removeAllView];
  289. // remove all Notification Messages
  290. [appDelegate.listOfNotifications removeAllObjects];
  291. // Initializations
  292. [appDelegate applicationInitialized];
  293. } else {
  294. // reload datasource
  295. [self reloadDatasource:_serverUrl];
  296. }
  297. }
  298. #pragma --------------------------------------------------------------------------------------------
  299. #pragma mark ==== DZNEmptyDataSetSource ====
  300. #pragma --------------------------------------------------------------------------------------------
  301. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  302. {
  303. if (_loadingFolder)
  304. return NO;
  305. else
  306. return YES;
  307. }
  308. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  309. {
  310. return [UIColor whiteColor];
  311. }
  312. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  313. {
  314. if (_isSearchMode)
  315. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"searchBig"] color:[NCBrandColor sharedInstance].brand];
  316. else
  317. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"filesNoFiles"] color:[NCBrandColor sharedInstance].brand];
  318. }
  319. - (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
  320. {
  321. if (_loadingFolder && _refreshControl.isRefreshing == NO) {
  322. UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  323. activityView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
  324. activityView.color = [NCBrandColor sharedInstance].brand;
  325. [activityView startAnimating];
  326. return activityView;
  327. }
  328. return nil;
  329. }
  330. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  331. {
  332. NSString *text;
  333. if (_isSearchMode) {
  334. text = _noFilesSearchTitle;
  335. } else {
  336. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  337. }
  338. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  339. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  340. }
  341. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  342. {
  343. NSString *text;
  344. if (_isSearchMode) {
  345. text = _noFilesSearchDescription;
  346. } else {
  347. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  348. }
  349. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  350. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  351. paragraph.alignment = NSTextAlignmentCenter;
  352. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  353. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  354. }
  355. #pragma --------------------------------------------------------------------------------------------
  356. #pragma mark ===== Text Field =====
  357. #pragma --------------------------------------------------------------------------------------------
  358. - (void)minCharTextFieldDidChange:(UITextField *)sender
  359. {
  360. UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
  361. if (alertController)
  362. {
  363. UITextField *fileName = alertController.textFields.firstObject;
  364. UIAlertAction *okAction = alertController.actions.lastObject;
  365. okAction.enabled = fileName.text.length > 0;
  366. }
  367. }
  368. - (void)textFieldDidBeginEditing:(UITextField *)textField{
  369. [textField selectAll:textField];
  370. }
  371. #pragma --------------------------------------------------------------------------------------------
  372. #pragma mark ===== Graphic Window =====
  373. #pragma --------------------------------------------------------------------------------------------
  374. - (void)createRefreshControl
  375. {
  376. _refreshControl = [UIRefreshControl new];
  377. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  378. _refreshControl.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1.0];
  379. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  380. [self setRefreshControl:_refreshControl];
  381. }
  382. - (void)deleteRefreshControl
  383. {
  384. [_refreshControl endRefreshing];
  385. self.refreshControl = nil;
  386. }
  387. - (void)refreshControlTarget
  388. {
  389. [self readFolder:_serverUrl];
  390. // Actuate `Peek` feedback (weak boom)
  391. AudioServicesPlaySystemSound(1519);
  392. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  393. }
  394. - (void)setTitle
  395. {
  396. // Color text self.navigationItem.title
  397. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  398. if (_isSelectedMode) {
  399. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  400. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  401. self.navigationItem.titleView = nil;
  402. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  403. } else {
  404. // we are in home : LOGO BRAND
  405. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  406. self.navigationItem.title = nil;
  407. if ([app.reachability isReachable] == NO)
  408. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogoOffline"]];
  409. else
  410. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"]];
  411. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  412. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo)];
  413. [singleTap setNumberOfTapsRequired:1];
  414. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  415. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  416. } else {
  417. self.navigationItem.title = _titleMain;
  418. }
  419. }
  420. }
  421. - (void)setUINavigationBarDefault
  422. {
  423. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  424. UIBarButtonItem *buttonMore, *buttonNotification;
  425. // =
  426. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationControllerMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  427. buttonMore.enabled = true;
  428. // <
  429. self.navigationController.navigationBar.hidden = NO;
  430. // Notification
  431. if ([app.listOfNotifications count] > 0) {
  432. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  433. buttonNotification.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  434. buttonNotification.enabled = true;
  435. }
  436. if (buttonNotification)
  437. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  438. else
  439. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  440. self.navigationItem.leftBarButtonItem = nil;
  441. }
  442. - (void)setUINavigationBarSelected
  443. {
  444. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  445. UIImage *icon = [UIImage imageNamed:@"navigationControllerMenu"];
  446. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  447. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  448. self.navigationItem.leftBarButtonItem = leftButton;
  449. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  450. }
  451. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  452. {
  453. [self closeAllMenu];
  454. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  455. }];
  456. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  457. }
  458. - (void)cancelSelect
  459. {
  460. [self tableViewSelect:NO];
  461. [app.reSelectMenu close];
  462. }
  463. - (void)closeAllMenu
  464. {
  465. // close Menu
  466. [app.reSelectMenu close];
  467. [app.reMainMenu close];
  468. // Close Menu Logo
  469. [CCMenuAccount dismissMenu];
  470. }
  471. #pragma --------------------------------------------------------------------------------------------
  472. #pragma mark ===== Document Picker =====
  473. #pragma --------------------------------------------------------------------------------------------
  474. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  475. {
  476. NSLog(@"Cancelled");
  477. }
  478. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  479. {
  480. NSLog(@"Cancelled");
  481. }
  482. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  483. {
  484. documentPicker.delegate = self;
  485. [self presentViewController:documentPicker animated:YES completion:nil];
  486. }
  487. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  488. {
  489. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  490. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  491. __block NSError *error;
  492. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  493. NSString *fileName = [url lastPathComponent];
  494. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  495. NSData *data = [NSData dataWithContentsOfURL:newURL];
  496. if (data && error == nil) {
  497. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  498. // Upload File
  499. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:_serverUrl cryptated:_isPickerCriptate onlyPlist:NO session:k_upload_session taskStatus: k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  500. } else {
  501. [app messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  502. }
  503. } else {
  504. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  505. }
  506. }];
  507. }
  508. }
  509. - (void)openImportDocumentPicker
  510. {
  511. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  512. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  513. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  514. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  515. documentProviderMenu.delegate = self;
  516. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  517. }
  518. #pragma --------------------------------------------------------------------------------------------
  519. #pragma mark ===== Assets Picker =====
  520. #pragma --------------------------------------------------------------------------------------------
  521. -(void)dismissFormUploadAssets
  522. {
  523. [self reloadDatasource];
  524. }
  525. - (void)openAssetsPickerController
  526. {
  527. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  528. checkmark.tintColor = [NCBrandColor sharedInstance].brand;
  529. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  530. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil];
  531. [app aspectNavigationControllerBar:navBar encrypted:NO online:YES hidden:NO];
  532. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  533. dispatch_async(dispatch_get_main_queue(), ^{
  534. // init picker
  535. CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
  536. // set delegate
  537. picker.delegate = self;
  538. // to show selection order
  539. //picker.showsSelectionIndex = YES;
  540. // to present picker as a form sheet in iPad
  541. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  542. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  543. // present picker
  544. [self presentViewController:picker animated:YES completion:nil];
  545. });
  546. }];
  547. }
  548. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  549. {
  550. [picker dismissViewControllerAnimated:YES completion:^{
  551. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] init:_titleMain serverUrl:_serverUrl assets:assets cryptated:_isPickerCriptate session:k_upload_session delegate:self];
  552. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  553. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  554. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  555. [self presentViewController:navigationController animated:YES completion:nil];
  556. }];
  557. }
  558. #pragma --------------------------------------------------------------------------------------------
  559. #pragma mark ===== Create New (OpenModel) =====
  560. #pragma --------------------------------------------------------------------------------------------
  561. - (void)openModel:(NSString *)tipo isNew:(BOOL)isnew
  562. {
  563. UIViewController *viewController;
  564. NSString *fileName, *uuid, *fileID, *serverUrl;
  565. NSIndexPath * index = [self.tableView indexPathForSelectedRow];
  566. [self.tableView deselectRowAtIndexPath:index animated:NO];
  567. if (isnew) {
  568. fileName = nil;
  569. uuid = [CCUtility getUUID];
  570. fileID = nil;
  571. serverUrl = _serverUrl;
  572. } else {
  573. fileName = _metadata.fileName;
  574. uuid = _metadata.uuid;
  575. fileID = _metadata.fileID;
  576. serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  577. }
  578. if ([tipo isEqualToString:@"cartadicredito"])
  579. viewController = [[CCCartaDiCredito alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  580. if ([tipo isEqualToString:@"bancomat"])
  581. viewController = [[CCBancomat alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  582. if ([tipo isEqualToString:@"contocorrente"])
  583. viewController = [[CCContoCorrente alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  584. if ([tipo isEqualToString:@"accountweb"])
  585. viewController = [[CCAccountWeb alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  586. if ([tipo isEqualToString:@"patenteguida"])
  587. viewController = [[CCPatenteGuida alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  588. if ([tipo isEqualToString:@"cartaidentita"])
  589. viewController = [[CCCartaIdentita alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  590. if ([tipo isEqualToString:@"passaporto"])
  591. viewController = [[CCPassaporto alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  592. if ([tipo isEqualToString:@"note"]) {
  593. viewController = [[CCNote alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  594. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  595. [self presentViewController:navigationController animated:YES completion:nil];
  596. } else {
  597. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  598. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  599. [self presentViewController:navigationController animated:YES completion:nil];
  600. }
  601. }
  602. // New folder or new photo or video
  603. - (void)returnCreate:(NSInteger)type
  604. {
  605. switch (type) {
  606. /* PLAIN */
  607. case k_returnCreateFolderPlain: {
  608. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  609. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  610. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  611. textField.autocapitalizationType = UITextAutocapitalizationTypeWords;
  612. }];
  613. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  614. NSLog(@"Cancel action");
  615. }];
  616. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  617. UITextField *fileName = alertController.textFields.firstObject;
  618. [self createFolder:fileName.text autoUploadDirectory:NO];
  619. }];
  620. okAction.enabled = NO;
  621. [alertController addAction:cancelAction];
  622. [alertController addAction:okAction];
  623. [self presentViewController:alertController animated:YES completion:nil];
  624. }
  625. break;
  626. case k_returnCreateFotoVideoPlain: {
  627. _isPickerCriptate = false;
  628. [self openAssetsPickerController];
  629. }
  630. break;
  631. case k_returnCreateFilePlain: {
  632. _isPickerCriptate = false;
  633. [self openImportDocumentPicker];
  634. }
  635. break;
  636. /* ENCRYPTED */
  637. case k_returnCreateFolderEncrypted: {
  638. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  639. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  640. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  641. }];
  642. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  643. NSLog(@"Cancel action");
  644. }];
  645. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  646. UITextField *fileName = alertController.textFields.firstObject;
  647. [self createFolderEncrypted:fileName.text];
  648. }];
  649. okAction.enabled = NO;
  650. [alertController addAction:cancelAction];
  651. [alertController addAction:okAction];
  652. [self presentViewController:alertController animated:YES completion:nil];
  653. }
  654. break;
  655. case k_returnCreateFotoVideoEncrypted: {
  656. _isPickerCriptate = true;
  657. [self openAssetsPickerController];
  658. }
  659. break;
  660. case k_returnCreateFileEncrypted: {
  661. _isPickerCriptate = true;
  662. [self openImportDocumentPicker];
  663. }
  664. break;
  665. /* UTILITY */
  666. case k_returnNote:
  667. [self openModel:@"note" isNew:true];
  668. break;
  669. case k_returnAccountWeb:
  670. [self openModel:@"accountweb" isNew:true];
  671. break;
  672. /* BANK */
  673. case k_returnCartaDiCredito:
  674. [self openModel:@"cartadicredito" isNew:true];
  675. break;
  676. case k_returnBancomat:
  677. [self openModel:@"bancomat" isNew:true];
  678. break;
  679. case k_returnContoCorrente:
  680. [self openModel:@"contocorrente" isNew:true];
  681. break;
  682. /* DOCUMENT */
  683. case k_returnPatenteGuida:
  684. [self openModel:@"patenteguida" isNew:true];
  685. break;
  686. case k_returnCartaIdentita:
  687. [self openModel:@"cartaidentita" isNew:true];
  688. break;
  689. case k_returnPassaporto:
  690. [self openModel:@"passaporto" isNew:true];
  691. break;
  692. }
  693. }
  694. #pragma --------------------------------------------------------------------------------------------
  695. #pragma mark ===== Save selected File =====
  696. #pragma --------------------------------------------------------------------------------------------
  697. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  698. {
  699. if (error)
  700. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  701. else
  702. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:error.code];
  703. }
  704. - (void)saveSelectedFiles
  705. {
  706. NSLog(@"[LOG] Start download selected files ...");
  707. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  708. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  709. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  710. for (tableMetadata *metadata in metadatas) {
  711. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file] && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  712. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  713. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  714. }
  715. }
  716. [_hud hideHud];
  717. });
  718. [self tableViewSelect:NO];
  719. }
  720. #pragma --------------------------------------------------------------------------------------------
  721. #pragma mark ===== Change Password =====
  722. #pragma --------------------------------------------------------------------------------------------
  723. - (void) loginSuccess:(NSInteger)loginType
  724. {
  725. [self readFolder:_serverUrl];
  726. }
  727. - (void)changePasswordAccount
  728. {
  729. // Brand
  730. if ([NCBrandOptions sharedInstance].use_login_web) {
  731. _loginWeb = [CCLoginWeb new];
  732. _loginWeb.delegate = self;
  733. _loginWeb.loginType = loginModifyPasswordUser;
  734. dispatch_async(dispatch_get_main_queue(), ^ {
  735. [_loginWeb presentModalWithDefaultTheme:self];
  736. });
  737. } else {
  738. _loginVC = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  739. _loginVC.delegate = self;
  740. _loginVC.loginType = loginModifyPasswordUser;
  741. [self presentViewController:_loginVC animated:YES completion:nil];
  742. }
  743. }
  744. #pragma mark -
  745. #pragma --------------------------------------------------------------------------------------------
  746. #pragma mark ===== Peek & Pop =====
  747. #pragma --------------------------------------------------------------------------------------------
  748. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  749. {
  750. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  751. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  752. if (metadata.thumbnailExists && !metadata.cryptated) {
  753. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  754. if (cell) {
  755. previewingContext.sourceRect = cell.frame;
  756. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  757. vc.delegate = self;
  758. vc.metadata = metadata;
  759. return vc;
  760. }
  761. }
  762. return nil;
  763. }
  764. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  765. {
  766. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  767. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  768. }
  769. #pragma mark -
  770. #pragma --------------------------------------------------------------------------------------------
  771. #pragma mark ==== External Sites ====
  772. #pragma --------------------------------------------------------------------------------------------
  773. - (void)getExternalSitesServerSuccess:(NSArray *)listOfExternalSites
  774. {
  775. [[NCManageDatabase sharedInstance] deleteExternalSites];
  776. for (OCExternalSites *tableExternalSites in listOfExternalSites)
  777. [[NCManageDatabase sharedInstance] addExternalSites:tableExternalSites];
  778. }
  779. - (void)getExternalSitesServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  780. {
  781. NSLog(@"[LOG] No External Sites found");
  782. }
  783. #pragma --------------------------------------------------------------------------------------------
  784. #pragma mark ==== Activity ====
  785. #pragma --------------------------------------------------------------------------------------------
  786. - (void)getActivityServerSuccess:(NSArray *)listOfActivity
  787. {
  788. [[NCManageDatabase sharedInstance] addActivityServer:listOfActivity];
  789. // Reload Activity Data Source
  790. [app.activeActivity reloadDatasource];
  791. }
  792. - (void)getActivityServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  793. {
  794. NSLog(@"[LOG] No Activity found");
  795. }
  796. #pragma --------------------------------------------------------------------------------------------
  797. #pragma mark ==== Notification ====
  798. #pragma --------------------------------------------------------------------------------------------
  799. - (void)getNotificationServerSuccess:(NSArray *)listOfNotifications
  800. {
  801. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  802. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  803. // Order by date
  804. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  805. OCNotifications *notification1 = obj1, *notification2 = obj2;
  806. return [notification2.date compare: notification1.date];
  807. }];
  808. // verify if listOfNotifications is changed
  809. NSString *old = @"", *new = @"";
  810. for (OCNotifications *notification in listOfNotifications)
  811. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  812. for (OCNotifications *notification in appDelegate.listOfNotifications)
  813. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  814. if (![new isEqualToString:old]) {
  815. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  816. // reload Notification view
  817. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"notificationReloadData" object:nil];
  818. }
  819. // Update NavigationBar
  820. if (!_isSelectedMode) {
  821. [self performSelectorOnMainThread:@selector(setUINavigationBarDefault) withObject:nil waitUntilDone:NO];
  822. }
  823. });
  824. }
  825. - (void)getNotificationServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  826. {
  827. // Update NavigationBar
  828. if (!_isSelectedMode)
  829. [self setUINavigationBarDefault];
  830. }
  831. - (void)viewNotification
  832. {
  833. if ([app.listOfNotifications count] > 0) {
  834. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  835. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  836. [self presentViewController:notificationVC animated:YES completion:nil];
  837. }
  838. }
  839. #pragma --------------------------------------------------------------------------------------------
  840. #pragma mark ==== User Profile ====
  841. #pragma --------------------------------------------------------------------------------------------
  842. - (void)getUserProfileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  843. {
  844. if (errorCode == 401)
  845. [self changePasswordAccount];
  846. }
  847. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  848. {
  849. [[NCManageDatabase sharedInstance] setAccountsUserProfile:userProfile];
  850. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  851. NSString *address = [NSString stringWithFormat:@"%@/index.php/avatar/%@/128", app.activeUrl, app.activeUser];
  852. UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  853. if (avatar)
  854. [UIImagePNGRepresentation(avatar) writeToFile:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] atomically:YES];
  855. else
  856. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] error:nil];
  857. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeUserProfile" object:nil];
  858. });
  859. }
  860. #pragma --------------------------------------------------------------------------------------------
  861. #pragma mark ==== Capabilities ====
  862. #pragma --------------------------------------------------------------------------------------------
  863. - (void)getCapabilitiesOfServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  864. {
  865. // Change Theming color
  866. [app settingThemingColorBrand];
  867. if (errorCode == 401)
  868. [self changePasswordAccount];
  869. }
  870. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  871. {
  872. // Update capabilities db
  873. [[NCManageDatabase sharedInstance] addCapabilities:capabilities];
  874. // ------ THEMING -----------------------------------------------------------------------
  875. // Download Theming Background & Change Theming color
  876. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  877. if ([NCBrandOptions sharedInstance].use_themingBackground == YES) {
  878. UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  879. if (themingBackground)
  880. [UIImagePNGRepresentation(themingBackground) writeToFile:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] atomically:YES];
  881. else
  882. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] error:nil];
  883. }
  884. dispatch_async(dispatch_get_main_queue(), ^{
  885. [app settingThemingColorBrand];
  886. });
  887. });
  888. // ------ SEARCH ------------------------------------------------------------------------
  889. // Search bar if change version
  890. if ([[NCManageDatabase sharedInstance] getServerVersion] != capabilities.versionMajor) {
  891. [self cancelSearchBar];
  892. }
  893. // ------ GET SERVICE SERVER ------------------------------------------------------------
  894. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  895. // Read External Sites
  896. if (capabilities.isExternalSitesServerEnabled) {
  897. metadataNet.action = actionGetExternalSitesServer;
  898. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  899. }
  900. // Read Share
  901. if (capabilities.isFilesSharingAPIEnabled) {
  902. [app.sharesID removeAllObjects];
  903. metadataNet.action = actionReadShareServer;
  904. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  905. }
  906. // Read Notification
  907. metadataNet.action = actionGetNotificationServer;
  908. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  909. // Read User Profile
  910. metadataNet.action = actionGetUserProfile;
  911. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  912. // Read Activity
  913. metadataNet.action = actionGetActivityServer;
  914. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  915. }
  916. #pragma mark -
  917. #pragma --------------------------------------------------------------------------------------------
  918. #pragma mark ==== Request Server Information ====
  919. #pragma --------------------------------------------------------------------------------------------
  920. - (void)requestServerCapabilities
  921. {
  922. // test
  923. if (app.activeAccount.length == 0)
  924. return;
  925. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  926. metadataNet.action = actionGetCapabilities;
  927. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  928. }
  929. #pragma mark -
  930. #pragma --------------------------------------------------------------------------------------------
  931. #pragma mark ==== Middleware Ping ====
  932. #pragma --------------------------------------------------------------------------------------------
  933. - (void)middlewarePing
  934. {
  935. // test
  936. if (app.activeAccount.length == 0)
  937. return;
  938. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  939. metadataNet.action = actionMiddlewarePing;
  940. metadataNet.serverUrl = [[NCBrandOptions sharedInstance] middlewarePingUrl];
  941. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  942. }
  943. #pragma mark -
  944. #pragma --------------------------------------------------------------------------------------------
  945. #pragma mark ==== Download Thumbnail Delegate ====
  946. #pragma --------------------------------------------------------------------------------------------
  947. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  948. {
  949. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  950. if (indexPath && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]]) {
  951. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  952. }
  953. }
  954. #pragma --------------------------------------------------------------------------------------------
  955. #pragma mark ==== Download ====
  956. #pragma --------------------------------------------------------------------------------------------
  957. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  958. {
  959. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  960. // File do not exists on server, remove in local
  961. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  962. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID] error:nil];
  963. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID] error:nil];
  964. if (metadata.directory && serverUrl) {
  965. NSString *dirForDelete = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  966. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:dirForDelete];
  967. }
  968. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID] clearDateReadDirectoryID:nil];
  969. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  970. }
  971. if ([selector isEqualToString:selectorLoadViewImage]) {
  972. dispatch_async(dispatch_get_main_queue(), ^{
  973. // Updating Detail
  974. if (app.activeDetail)
  975. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  976. // Updating Photos
  977. if (app.activePhotos)
  978. [app.activePhotos downloadFileFailure:errorCode];
  979. });
  980. } else {
  981. if (errorCode != kCFURLErrorCancelled)
  982. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  983. }
  984. [self reloadDatasource:serverUrl];
  985. }
  986. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  987. {
  988. __block tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  989. if (metadata == nil)
  990. return;
  991. // Download
  992. if ([selector isEqualToString:selectorDownloadFile]) {
  993. [self reloadDatasource:serverUrl];
  994. }
  995. // Synchronized
  996. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  997. [self reloadDatasource:serverUrl];
  998. }
  999. // add Favorite
  1000. if ([selector isEqualToString:selectorAddFavorite]) {
  1001. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  1002. }
  1003. // encrypted file
  1004. if ([selector isEqualToString:selectorEncryptFile]) {
  1005. [self encryptedFile:metadata];
  1006. }
  1007. // decrypted file
  1008. if ([selector isEqualToString:selectorDecryptFile]) {
  1009. [self decryptedFile:metadata];
  1010. }
  1011. // open View File
  1012. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1013. [self reloadDatasource:serverUrl];
  1014. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  1015. selector = selectorOpenIn;
  1016. //[self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  1017. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  1018. selector = selectorOpenIn;
  1019. } else {
  1020. _metadata = metadata;
  1021. if ([self shouldPerformSegue])
  1022. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  1023. }
  1024. }
  1025. // addLocal
  1026. if ([selector isEqualToString:selectorAddLocal]) {
  1027. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1028. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  1029. [CCGraphics saveIcoWithEtag:metadata.fileNamePrint image:image writeToFile:nil copy:YES move:NO fromPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/.%@.ico", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1030. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  1031. [self reloadDatasource:serverUrl];
  1032. }
  1033. // Open with...
  1034. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1035. [self reloadDatasource:serverUrl];
  1036. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1037. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1038. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint]];
  1039. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  1040. _docController.delegate = self;
  1041. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  1042. }
  1043. // Save to Photo Album
  1044. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1045. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1046. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  1047. UIImage *image = [UIImage imageWithContentsOfFile:file];
  1048. if (image)
  1049. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1050. else
  1051. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1052. }
  1053. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  1054. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1055. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint])) {
  1056. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1057. } else {
  1058. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1059. }
  1060. }
  1061. [self reloadDatasource:serverUrl];
  1062. }
  1063. // Copy File
  1064. if ([selector isEqualToString:selectorLoadCopy]) {
  1065. [self reloadDatasource:serverUrl];
  1066. [self copyFileToPasteboard:metadata];
  1067. }
  1068. // download and view a template
  1069. if ([selector isEqualToString:selectorLoadModelView]) {
  1070. // se è un template aggiorniamo anche nel FileSystem
  1071. if ([metadata.type isEqualToString: k_metadataType_template]) {
  1072. [[NCManageDatabase sharedInstance] setLocalFileWithFileID:metadata.fileID date:metadata.date exifDate:nil exifLatitude:nil exifLongitude:nil fileName:nil fileNamePrint:metadata.fileNamePrint];
  1073. }
  1074. [self openModel:metadata.model isNew:false];
  1075. [self reloadDatasource:serverUrl];
  1076. }
  1077. //download file plist
  1078. if ([selector isEqualToString:selectorLoadPlist]) {
  1079. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1080. long countSelectorLoadPlist = 0;
  1081. for (NSOperation *operation in [app.netQueue operations]) {
  1082. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1083. countSelectorLoadPlist++;
  1084. }
  1085. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % k_maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:[[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl]]) {
  1086. dispatch_async(dispatch_get_main_queue(), ^{
  1087. [self reloadDatasource:serverUrl];
  1088. });
  1089. }
  1090. });
  1091. }
  1092. //selectorLoadViewImage
  1093. if ([selector isEqualToString:selectorLoadViewImage]) {
  1094. // Detail
  1095. if (app.activeDetail)
  1096. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1097. // Photos
  1098. if (app.activePhotos)
  1099. [app.activePhotos downloadFileSuccess:metadata];
  1100. [self reloadDatasource:serverUrl];
  1101. }
  1102. // if exists postselector call self with selectorPost
  1103. if ([selectorPost length] > 0)
  1104. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1105. }
  1106. - (void)downloadSelectedFilesFolders
  1107. {
  1108. NSLog(@"[LOG] Start download selected ...");
  1109. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1110. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1111. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1112. for (tableMetadata *metadata in selectedMetadatas) {
  1113. if ([metadata.type isEqualToString: k_metadataType_file]) {
  1114. if (metadata.directory) {
  1115. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1116. serverUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  1117. [[CCSynchronize sharedSynchronize] synchronizedFolder:serverUrl selector:selectorReadFolderWithDownload];
  1118. } else {
  1119. [[CCSynchronize sharedSynchronize] synchronizedFile:metadata selector:selectorReadFileWithDownload];
  1120. }
  1121. }
  1122. }
  1123. [_hud hideHud];
  1124. });
  1125. [self tableViewSelect:NO];
  1126. }
  1127. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1128. {
  1129. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", app.activeAccount, directoryID] sorted:nil ascending:NO];
  1130. for (tableMetadata *metadata in metadatas) {
  1131. if ([CCUtility isCryptoPlistString:metadata.fileName] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName]] == NO && [metadata.session length] == 0) {
  1132. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1133. metadataNet.action = actionDownloadFile;
  1134. metadataNet.downloadData = NO;
  1135. metadataNet.downloadPlist = YES;
  1136. metadataNet.fileID = metadata.fileID;
  1137. metadataNet.selector = selectorLoadPlist;
  1138. metadataNet.serverUrl = serverUrl;
  1139. metadataNet.session = k_download_session_foreground;
  1140. metadataNet.taskStatus = k_taskStatusResume;
  1141. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1142. //[[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selectorLoadPlist selectorPost:nil session:k_download_session_foreground taskStatus:k_taskStatusResume delegate:self];
  1143. }
  1144. }
  1145. }
  1146. #pragma --------------------------------------------------------------------------------------------
  1147. #pragma mark ===== Upload new Photos/Videos =====
  1148. #pragma --------------------------------------------------------------------------------------------
  1149. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1150. {
  1151. // Auto Upload
  1152. if([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll]) {
  1153. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1154. // ONLY BACKGROUND
  1155. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1156. } else {
  1157. // ONLY FOREFROUND
  1158. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1159. }
  1160. }
  1161. // Read File test do not exists
  1162. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1163. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1164. // reUpload
  1165. if (metadata)
  1166. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1167. }
  1168. // Print error
  1169. else if (errorCode != kCFURLErrorCancelled && errorCode != 403) {
  1170. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1171. }
  1172. [self reloadDatasource:serverUrl];
  1173. }
  1174. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1175. {
  1176. // Auto Upload
  1177. if([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll]) {
  1178. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1179. // ONLY BACKGROUND
  1180. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1181. } else {
  1182. // ONLY FOREFROUND
  1183. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1184. }
  1185. }
  1186. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1187. [self readFolder:serverUrl];
  1188. } else {
  1189. [self reloadDatasource:serverUrl];
  1190. }
  1191. }
  1192. //
  1193. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1194. //
  1195. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1196. {
  1197. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1198. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:cryptated], [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1199. });
  1200. }
  1201. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1202. {
  1203. NSArray *assets = [arguments objectAtIndex:0];
  1204. NSString *serverUrl = [arguments objectAtIndex:1];
  1205. BOOL cryptated = [[arguments objectAtIndex:2] boolValue];
  1206. BOOL useSubFolder = [[arguments objectAtIndex:3] boolValue];
  1207. NSString *session = [arguments objectAtIndex:4];
  1208. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  1209. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  1210. // Create the folder for Photos & if request the subfolders
  1211. if (![[NCAutoUpload sharedInstance] createFolderSubFolderAutoUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:(PHFetchResult *)assets selector:selectorUploadFile])
  1212. return;
  1213. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1214. for (PHAsset *asset in assets) {
  1215. NSString *fileName = [CCUtility createFileNameFromAsset:asset key: k_keyFileNameMask];
  1216. NSDate *assetDate = asset.creationDate;
  1217. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1218. // Create serverUrl if use sub folder
  1219. if (useSubFolder) {
  1220. [formatter setDateFormat:@"yyyy"];
  1221. NSString *yearString = [formatter stringFromDate:assetDate];
  1222. [formatter setDateFormat:@"MM"];
  1223. NSString *monthString = [formatter stringFromDate:assetDate];
  1224. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  1225. }
  1226. // Check if is in upload
  1227. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@ AND session != ''", app.activeAccount, directoryID, fileName];
  1228. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1229. if ([isRecordInSessions count] > 0) {
  1230. // next upload
  1231. continue;
  1232. } else {
  1233. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1234. if (cryptated) {
  1235. metadataNet.action = actionUploadAsset;
  1236. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1237. metadataNet.cryptated = cryptated;
  1238. metadataNet.fileName = fileName;
  1239. metadataNet.session = session;
  1240. metadataNet.selector = selectorUploadFile;
  1241. metadataNet.selectorPost = nil;
  1242. metadataNet.serverUrl = serverUrl;
  1243. metadataNet.taskStatus = k_taskStatusResume;
  1244. } else {
  1245. metadataNet.action = actionReadFile;
  1246. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1247. metadataNet.cryptated = cryptated;
  1248. metadataNet.fileName = fileName;
  1249. metadataNet.session = session;
  1250. metadataNet.selector = selectorReadFileUploadFile;
  1251. metadataNet.serverUrl = serverUrl;
  1252. }
  1253. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1254. }
  1255. }
  1256. }
  1257. #pragma --------------------------------------------------------------------------------------------
  1258. #pragma mark ==== Read File ====
  1259. #pragma --------------------------------------------------------------------------------------------
  1260. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1261. {
  1262. // Read Folder
  1263. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  1264. //[self readFolderWithForced:NO serverUrl:metadataNet.serverUrl];
  1265. }
  1266. // UploadFile
  1267. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1268. // File not exists
  1269. if (errorCode == 404) {
  1270. metadataNet.action = actionUploadAsset;
  1271. metadataNet.errorCode = 0;
  1272. metadataNet.selector = selectorUploadFile;
  1273. metadataNet.selectorPost = nil;
  1274. metadataNet.taskStatus = k_taskStatusResume;
  1275. if ([metadataNet.session containsString:@"wwan"])
  1276. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1277. else
  1278. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1279. } else {
  1280. // error ho many retry befor notification and go to on next asses
  1281. if (metadataNet.errorRetry < 3) {
  1282. // Retry read file
  1283. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1284. } else {
  1285. // STOP check file, view message error
  1286. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1287. }
  1288. }
  1289. }
  1290. }
  1291. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1292. {
  1293. // Read Folder
  1294. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  1295. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", metadataNet.account, metadataNet.serverUrl]];
  1296. if ([metadata.etag isEqualToString:directory.etag] == NO) {
  1297. [self readFolder:metadataNet.serverUrl];
  1298. }
  1299. }
  1300. // UploadFile
  1301. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1302. metadataNet.action = actionUploadAsset;
  1303. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1304. metadataNet.selector = selectorUploadFile;
  1305. metadataNet.selectorPost = nil;
  1306. metadataNet.taskStatus = k_taskStatusResume;
  1307. if ([metadataNet.session containsString:@"wwan"])
  1308. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1309. else
  1310. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1311. }
  1312. }
  1313. - (void)readFileReloadFolder
  1314. {
  1315. if (!_serverUrl || !app.activeAccount || app.maintenanceMode)
  1316. return;
  1317. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1318. metadataNet.action = actionReadFile;
  1319. metadataNet.priority = NSOperationQueuePriorityHigh;
  1320. metadataNet.selector = selectorReadFileReloadFolder;
  1321. metadataNet.serverUrl = _serverUrl;
  1322. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1323. }
  1324. #pragma --------------------------------------------------------------------------------------------
  1325. #pragma mark ==== Read Folder ====
  1326. #pragma --------------------------------------------------------------------------------------------
  1327. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1328. {
  1329. // verify active user
  1330. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1331. _loadingFolder = NO;
  1332. [self tableViewReloadData];
  1333. [_refreshControl endRefreshing];
  1334. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1335. if (message && [record.account isEqualToString:metadataNet.account])
  1336. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1337. [self reloadDatasource:metadataNet.serverUrl];
  1338. if (errorCode == 401)
  1339. [self changePasswordAccount];
  1340. }
  1341. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet metadataFolder:(tableMetadata *)metadataFolder metadatas:(NSArray *)metadatas
  1342. {
  1343. // verify active user
  1344. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1345. if (![record.account isEqualToString:metadataNet.account])
  1346. return;
  1347. // save father e update permission
  1348. if(!_isSearchMode && metadataFolder)
  1349. _fatherPermission = metadataFolder.permissions;
  1350. NSArray *recordsInSessions;
  1351. NSMutableArray *metadatasToInsertInDB = [NSMutableArray new];
  1352. if (_isSearchMode) {
  1353. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", metadataNet.account] sorted:nil ascending:NO];
  1354. } else {
  1355. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:metadataNet.serverUrl serverUrlTo:nil etag:metadataFolder.etag];
  1356. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", metadataNet.account, metadataNet.directoryID] clearDateReadDirectoryID:metadataNet.directoryID];
  1357. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session != ''", metadataNet.account, metadataNet.directoryID] sorted:nil ascending:NO];
  1358. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithDirectoryID:metadataNet.directoryID];
  1359. }
  1360. for (tableMetadata *metadata in metadatas) {
  1361. // type of file
  1362. NSInteger typeFilename = [CCUtility getTypeFileName:metadata.fileName];
  1363. // if crypto do not insert
  1364. if (typeFilename == k_metadataTypeFilenameCrypto) continue;
  1365. // verify if the record encrypted has plist + crypto
  1366. if (typeFilename == k_metadataTypeFilenamePlist && metadata.directory == NO) {
  1367. BOOL isCryptoComplete = NO;
  1368. NSString *fileNameCrypto = [CCUtility trasformedFileNamePlistInCrypto:metadata.fileName];
  1369. for (tableMetadata *completeMetadata in metadatas) {
  1370. if (completeMetadata.cryptated == NO) continue;
  1371. else if ([completeMetadata.fileName isEqualToString:fileNameCrypto]) {
  1372. isCryptoComplete = YES;
  1373. break;
  1374. }
  1375. }
  1376. if (isCryptoComplete == NO) continue;
  1377. }
  1378. // verify if the record is in download/upload progress
  1379. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1380. tableMetadata *metadataTransfer = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@", app.activeAccount, metadataNet.directoryID, metadata.fileName]];
  1381. // is in Download or Upload
  1382. if ([metadataTransfer.session containsString:@"upload"] || [metadataTransfer.session containsString:@"download"]) {
  1383. continue;
  1384. }
  1385. }
  1386. // Insert in Array
  1387. [metadatasToInsertInDB addObject:metadata];
  1388. }
  1389. // insert in Database
  1390. metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatasToInsertInDB activeUrl:app.activeUrl serverUrl:metadataNet.serverUrl];
  1391. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1392. // read plist
  1393. if (!_isSearchMode)
  1394. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1395. // File is changed ??
  1396. if (!_isSearchMode && metadatasToInsertInDB)
  1397. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl account:app.activeAccount withDownload:NO];
  1398. });
  1399. // Search Mode
  1400. if (_isSearchMode) {
  1401. // Fix managed -> Unmanaged _searchResultMetadatas
  1402. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasToInsertInDB];
  1403. [self reloadDatasource:metadataNet.serverUrl];
  1404. }
  1405. // this is the same directory
  1406. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1407. // reload
  1408. [self reloadDatasource:metadataNet.serverUrl];
  1409. // stoprefresh
  1410. [_refreshControl endRefreshing];
  1411. // Enable change user
  1412. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1413. _loadingFolder = NO;
  1414. [self tableViewReloadData];
  1415. }
  1416. }
  1417. - (void)readFolder:(NSString *)serverUrl
  1418. {
  1419. // init control
  1420. if (!serverUrl || !app.activeAccount || app.maintenanceMode) {
  1421. [_refreshControl endRefreshing];
  1422. return;
  1423. }
  1424. // Search Mode
  1425. if (_isSearchMode) {
  1426. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1427. _searchFileName = @""; // forced reload searchg
  1428. [self updateSearchResultsForSearchController:self.searchController];
  1429. return;
  1430. }
  1431. _loadingFolder = YES;
  1432. [self tableViewReloadData];
  1433. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, serverUrl]];
  1434. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1435. metadataNet.action = actionReadFolder;
  1436. metadataNet.date = [NSDate date];
  1437. metadataNet.directoryID = directory.directoryID;
  1438. metadataNet.priority = NSOperationQueuePriorityHigh;
  1439. metadataNet.selector = selectorReadFolder;
  1440. metadataNet.serverUrl = serverUrl;
  1441. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1442. }
  1443. #pragma mark -
  1444. #pragma --------------------------------------------------------------------------------------------
  1445. #pragma mark ===== Search =====
  1446. #pragma --------------------------------------------------------------------------------------------
  1447. -(void)searchStartTimer
  1448. {
  1449. NSString *home = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  1450. [[CCActions sharedInstance] search:home fileName:_searchFileName depth:_depth date:nil selector:selectorSearch delegate:self];
  1451. _noFilesSearchTitle = @"";
  1452. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1453. [self.tableView reloadEmptyDataSet];
  1454. }
  1455. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1456. {
  1457. [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
  1458. _isSearchMode = YES;
  1459. [self deleteRefreshControl];
  1460. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1461. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1462. _searchFileName = fileName;
  1463. // First : filter
  1464. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1465. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID = %@ AND account = %@ AND fileNamePrint CONTAINS[cd] %@", directoryID, app.activeAccount, fileName];
  1466. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1467. [_searchResultMetadatas removeAllObjects];
  1468. for (tableMetadata *record in records)
  1469. [_searchResultMetadatas addObject:record];
  1470. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1471. metadataNet.account = app.activeAccount;
  1472. metadataNet.directoryID = directoryID;
  1473. metadataNet.selector = selectorSearch;
  1474. metadataNet.serverUrl = _serverUrl;
  1475. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:_searchResultMetadatas];
  1476. // Version >= 12
  1477. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  1478. [_timerWaitInput invalidate];
  1479. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1480. }
  1481. }
  1482. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1483. [self reloadDatasource];
  1484. }
  1485. }
  1486. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1487. {
  1488. [self cancelSearchBar];
  1489. [self readFolder:_serverUrl];
  1490. }
  1491. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1492. {
  1493. _searchFileName = @"";
  1494. if (message)
  1495. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1496. }
  1497. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1498. {
  1499. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1500. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:metadatas];
  1501. }
  1502. - (void)cancelSearchBar
  1503. {
  1504. if (self.searchController.active) {
  1505. [self.searchController setActive:NO];
  1506. [self createRefreshControl];
  1507. _isSearchMode = NO;
  1508. _searchFileName = @"";
  1509. _dateReadDataSource = nil;
  1510. _searchResultMetadatas = [NSMutableArray new];
  1511. [self reloadDatasource];
  1512. }
  1513. [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
  1514. }
  1515. #pragma mark -
  1516. #pragma --------------------------------------------------------------------------------------------
  1517. #pragma mark ===== Delete File or Folder =====
  1518. #pragma --------------------------------------------------------------------------------------------
  1519. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1520. {
  1521. [self deleteFileOrFolderSuccess:metadataNet];
  1522. }
  1523. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1524. {
  1525. [_queueSelector removeObject:metadataNet.selector];
  1526. if ([_queueSelector count] == 0) {
  1527. [_hud hideHud];
  1528. // next
  1529. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1530. if ([_selectedFileIDsMetadatas count] > 0) {
  1531. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1532. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1533. } else {
  1534. // End Select Table View
  1535. [self tableViewSelect:NO];
  1536. // Reload
  1537. if (_isSearchMode)
  1538. [self readFolder:metadataNet.serverUrl];
  1539. else
  1540. [self reloadDatasource:metadataNet.serverUrl];
  1541. }
  1542. }
  1543. }
  1544. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1545. {
  1546. if (metadata.cryptated) {
  1547. [_queueSelector addObject:selectorDeleteCrypto];
  1548. [_queueSelector addObject:selectorDeletePlist];
  1549. } else {
  1550. [_queueSelector addObject:selectorDelete];
  1551. }
  1552. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1553. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1554. }
  1555. - (void)deleteFile
  1556. {
  1557. [_queueSelector removeAllObjects];
  1558. if ([_selectedFileIDsMetadatas count] > 0) {
  1559. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1560. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1561. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1562. } else {
  1563. _numSelectedFileIDsMetadatas = 1;
  1564. [self deleteFileOrFolder:_metadata numFile:1 ofFile:_numSelectedFileIDsMetadatas];
  1565. }
  1566. }
  1567. #pragma --------------------------------------------------------------------------------------------
  1568. #pragma mark ===== Rename / Move =====
  1569. #pragma --------------------------------------------------------------------------------------------
  1570. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1571. {
  1572. [self readFolder:metadataNet.serverUrl];
  1573. }
  1574. - (void)renameFile:(NSArray *)arguments
  1575. {
  1576. tableMetadata* metadata = [arguments objectAtIndex:0];
  1577. NSString *fileName = [arguments objectAtIndex:1];
  1578. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1579. }
  1580. - (void)renameNote:(NSArray *)arguments
  1581. {
  1582. tableMetadata* metadata = [arguments objectAtIndex:0];
  1583. NSString *fileName = [arguments objectAtIndex:1];
  1584. CCTemplates *templates = [[CCTemplates alloc] init];
  1585. NSMutableDictionary *field = [[CCCrypto sharedManager] getDictionaryEncrypted:metadata.fileName uuid:metadata.uuid isLocal:NO directoryUser:app.directoryUser];
  1586. NSString *fileNameModel = [templates salvaNote:[field objectForKey:@"note"] titolo:fileName fileName:metadata.fileName uuid:metadata.uuid];
  1587. if (fileNameModel) {
  1588. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1589. metadataNet.action = actionUploadTemplate;
  1590. metadataNet.fileName = [CCUtility trasformedFileNamePlistInCrypto:fileNameModel];
  1591. metadataNet.fileNamePrint = fileName;
  1592. metadataNet.etag = metadata.etag;
  1593. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1594. metadataNet.session = k_upload_session_foreground;
  1595. metadataNet.taskStatus = k_taskStatusResume;
  1596. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1597. }
  1598. }
  1599. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1600. {
  1601. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1602. [_hud hideHud];
  1603. if (message)
  1604. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1605. // End Select Table View
  1606. [self tableViewSelect:NO];
  1607. // reload Datasource
  1608. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1609. [self readFolder:metadataNet.serverUrl];
  1610. else
  1611. [self reloadDatasource];
  1612. }
  1613. }
  1614. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1615. {
  1616. [_queueSelector removeObject:metadataNet.selector];
  1617. if ([_queueSelector count] == 0) {
  1618. [_hud hideHud];
  1619. NSString *fileName = [CCUtility trasformedFileNameCryptoInPlist:metadataNet.fileName];
  1620. NSString *directoryID = metadataNet.directoryID;
  1621. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1622. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1623. // FILE -> Metadata
  1624. if (metadataNet.directory == NO)
  1625. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1626. // DIRECTORY -> Directory - CCMetadata
  1627. if (metadataNet.directory == YES) {
  1628. // delete all dir / subdir
  1629. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1630. // move metadata
  1631. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1632. // Add new directory
  1633. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1634. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:@""];
  1635. }
  1636. // next
  1637. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1638. if ([_selectedFileIDsMetadatas count] > 0) {
  1639. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1640. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1641. } else {
  1642. // End Select Table View
  1643. [self tableViewSelect:NO];
  1644. // reload Datasource
  1645. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1646. [self readFolder:metadataNet.serverUrl];
  1647. else
  1648. [self reloadDatasource];
  1649. }
  1650. }
  1651. }
  1652. - (void)moveFileOrFolderMetadata:(NSArray *)arguments
  1653. {
  1654. tableMetadata *metadata = [arguments objectAtIndex:0];
  1655. NSString *serverUrlTo = [arguments objectAtIndex:1];
  1656. NSInteger numFile = [[arguments objectAtIndex:2] integerValue];
  1657. NSInteger ofFile = [[arguments objectAtIndex:3] integerValue];
  1658. // Plain
  1659. if (metadata.cryptated == NO) {
  1660. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withPassword:app.activePassword withUrl:app.activeUrl isCryptoCloudMode:NO];
  1661. NSError *error = [ocNetworking readFileSync:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName]];
  1662. if(!error) {
  1663. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1664. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1665. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1666. }];
  1667. [alert addAction:ok];
  1668. [self presentViewController:alert animated:YES completion:nil];
  1669. });
  1670. // End Select Table View
  1671. [self tableViewSelect:NO];
  1672. // reload Datasource
  1673. [self readFileReloadFolder];
  1674. return;
  1675. }
  1676. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1677. metadataNet.action = actionMoveFileOrFolder;
  1678. metadataNet.directory = metadata.directory;
  1679. metadataNet.fileID = metadata.fileID;
  1680. metadataNet.directoryID = metadata.directoryID;
  1681. metadataNet.directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1682. metadataNet.fileName = metadata.fileName;
  1683. metadataNet.fileNamePrint = metadataNet.fileNamePrint;
  1684. metadataNet.fileNameTo = metadata.fileName;
  1685. metadataNet.etag = metadata.etag;
  1686. metadataNet.selector = selectorMove;
  1687. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1688. metadataNet.serverUrlTo = serverUrlTo;
  1689. [_queueSelector addObject:metadataNet.selector];
  1690. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1691. }
  1692. // cyptated
  1693. if (metadata.cryptated == YES) {
  1694. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1695. metadataNet.action = actionMoveFileOrFolder;
  1696. metadataNet.directory = metadata.directory;
  1697. metadataNet.fileID = metadata.fileID;
  1698. metadataNet.directoryID = metadata.directoryID;
  1699. metadataNet.directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1700. metadataNet.fileNamePrint = metadata.fileNamePrint;
  1701. metadataNet.etag = metadata.etag;
  1702. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1703. metadataNet.serverUrlTo = serverUrlTo;
  1704. // data
  1705. metadataNet.fileName = metadata.fileNameData;
  1706. metadataNet.fileNameTo = metadata.fileNameData;
  1707. metadataNet.selector = selectorMoveCrypto;
  1708. [_queueSelector addObject:metadataNet.selector];
  1709. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1710. // plist
  1711. metadataNet.fileName = metadata.fileName;
  1712. metadataNet.fileNameTo = metadata.fileName;
  1713. metadataNet.selector = selectorMovePlist;
  1714. [_queueSelector addObject:metadataNet.selector];
  1715. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1716. }
  1717. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1718. }
  1719. // DELEGATE : Move
  1720. - (void)dismissMove
  1721. {
  1722. [self reloadDatasource];
  1723. }
  1724. // DELEGATE : Move
  1725. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title
  1726. {
  1727. [_queueSelector removeAllObjects];
  1728. if ([_selectedFileIDsMetadatas count] > 0) {
  1729. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1730. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1731. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1732. } else {
  1733. _numSelectedFileIDsMetadatas = 1;
  1734. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[_metadata, serverUrlTo, [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1735. }
  1736. }
  1737. - (void)moveOpenWindow:(NSArray *)indexPaths
  1738. {
  1739. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1740. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1741. viewController.delegate = self;
  1742. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1743. viewController.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  1744. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1745. viewController.tintColorTitle = [NCBrandColor sharedInstance].navigationBarText;
  1746. viewController.networkingOperationQueue = app.netQueue;
  1747. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1748. [self presentViewController:navigationController animated:YES completion:nil];
  1749. }
  1750. #pragma --------------------------------------------------------------------------------------------
  1751. #pragma mark ===== Create folder =====
  1752. #pragma --------------------------------------------------------------------------------------------
  1753. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1754. {
  1755. [_hud hideHud];
  1756. if (message)
  1757. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1758. }
  1759. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1760. {
  1761. [_hud hideHud];
  1762. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1763. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:@""];
  1764. // Load Folder or the Datasource
  1765. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced]) {
  1766. [self readFolder:metadataNet.serverUrl];
  1767. } else {
  1768. [self reloadDatasource:metadataNet.serverUrl];
  1769. }
  1770. }
  1771. - (void)createFolder:(NSString *)fileNameFolder autoUploadDirectory:(BOOL)autoUploadDirectory
  1772. {
  1773. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1774. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1775. if (![fileNameFolder length]) return;
  1776. if (autoUploadDirectory) metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  1777. else metadataNet.serverUrl = _serverUrl;
  1778. metadataNet.action = actionCreateFolder;
  1779. if (autoUploadDirectory)
  1780. metadataNet.options = @"folderAutoUpload";
  1781. metadataNet.fileName = fileNameFolder;
  1782. metadataNet.selector = selectorCreateFolder;
  1783. metadataNet.selectorPost = selectorReadFolderForced;
  1784. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1785. if (!autoUploadDirectory)
  1786. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1787. }
  1788. - (void)createFolderEncrypted:(NSString *)fileNameFolder
  1789. {
  1790. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1791. NSString *fileNamePlist;
  1792. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1793. if (![fileNameFolder length]) return;
  1794. NSString *title = [AESCrypt encrypt:fileNameFolder password:[[CCCrypto sharedManager] getKeyPasscode:[CCUtility getUUID]]];
  1795. fileNamePlist = [[CCCrypto sharedManager] createFilenameEncryptor:fileNameFolder uuid:[CCUtility getUUID]];
  1796. [[CCCrypto sharedManager] createFilePlist:[NSTemporaryDirectory() stringByAppendingString:fileNamePlist] title:title len:0 directory:true uuid:[CCUtility getUUID] nameCurrentDevice:[CCUtility getNameCurrentDevice] icon:@""];
  1797. // Create folder
  1798. metadataNet.action = actionCreateFolder;
  1799. metadataNet.fileName = fileNamePlist;
  1800. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1801. metadataNet.selector = selectorCreateFolder;
  1802. metadataNet.serverUrl = _serverUrl;
  1803. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1804. // upload plist file
  1805. metadataNet.action = actionUploadOnlyPlist;
  1806. metadataNet.fileName = [fileNamePlist stringByAppendingString:@".plist"];
  1807. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1808. metadataNet.selectorPost = selectorReadFolderForced;
  1809. metadataNet.serverUrl = _serverUrl;
  1810. metadataNet.session = k_upload_session_foreground;
  1811. metadataNet.taskStatus = k_taskStatusResume;
  1812. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1813. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1814. }
  1815. - (void)createFolderAutoUpload
  1816. {
  1817. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  1818. [self createFolder:autoUploadFileName autoUploadDirectory:YES];
  1819. }
  1820. #pragma --------------------------------------------------------------------------------------------
  1821. #pragma mark ===== Encrypted / Decrypted Folder =====
  1822. #pragma --------------------------------------------------------------------------------------------
  1823. - (void)encyptedDecryptedFolder
  1824. {
  1825. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  1826. if (_metadata.cryptated) {
  1827. // DECRYPTED
  1828. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1829. //-------------------------- RENAME -------------------------------------------//
  1830. metadataNet.action = actionMoveFileOrFolder;
  1831. metadataNet.fileID = _metadata.fileID;
  1832. metadataNet.fileName = _metadata.fileNameData;
  1833. metadataNet.fileNameTo = _metadata.fileNamePrint;
  1834. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1835. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1836. metadataNet.selector = selectorRename;
  1837. metadataNet.serverUrl = serverUrl;
  1838. metadataNet.serverUrlTo = serverUrl;
  1839. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1840. //-------------------------- DELETE -------------------------------------------//
  1841. metadataNet.action = actionDeleteFileDirectory;
  1842. metadataNet.fileID = _metadata.fileID;
  1843. metadataNet.fileName = _metadata.fileName;
  1844. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1845. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1846. metadataNet.selector = selectorDeletePlist;
  1847. metadataNet.selectorPost = selectorReadFolderForced;
  1848. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1849. } else {
  1850. // ENCRYPTED
  1851. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1852. // Create File Plist
  1853. NSString *fileNameCrypto = [[CCCrypto sharedManager] createFileDirectoryPlist:_metadata];
  1854. //-------------------------- RENAME -------------------------------------------//
  1855. metadataNet.action = actionMoveFileOrFolder;
  1856. metadataNet.fileID = _metadata.fileID;
  1857. metadataNet.fileName = _metadata.fileName;
  1858. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1859. metadataNet.fileNameTo = fileNameCrypto;
  1860. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1861. metadataNet.selector = selectorRename;
  1862. metadataNet.serverUrl = serverUrl;
  1863. metadataNet.serverUrlTo = serverUrl;
  1864. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1865. //-------------------------- UPLOAD -------------------------------------------//
  1866. metadataNet.action = actionUploadOnlyPlist;
  1867. metadataNet.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  1868. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1869. metadataNet.selectorPost = selectorReadFolderForced;
  1870. metadataNet.serverUrl = serverUrl;
  1871. metadataNet.session = k_upload_session_foreground;
  1872. metadataNet.taskStatus = k_taskStatusResume;
  1873. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1874. }
  1875. }
  1876. #pragma --------------------------------------------------------------------------------------------
  1877. #pragma mark ===== Encrypted/Decrypted File =====
  1878. #pragma --------------------------------------------------------------------------------------------
  1879. - (void)encryptedSelectedFiles
  1880. {
  1881. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1882. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1883. for (tableMetadata *metadata in selectedMetadatas) {
  1884. if (metadata.cryptated == NO && metadata.directory == NO)
  1885. [metadatas addObject:metadata];
  1886. }
  1887. if ([metadatas count] > 0) {
  1888. NSLog(@"[LOG] Start encrypted selected files ...");
  1889. for (tableMetadata* metadata in metadatas) {
  1890. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1891. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorEncryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1892. }
  1893. }
  1894. [self tableViewSelect:NO];
  1895. }
  1896. - (void)decryptedSelectedFiles
  1897. {
  1898. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1899. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1900. for (tableMetadata *metadata in selectedMetadatas) {
  1901. if (metadata.cryptated == YES && metadata.directory == NO && [metadata.model length] == 0)
  1902. [metadatas addObject:metadata];
  1903. }
  1904. if ([metadatas count] > 0) {
  1905. NSLog(@"[LOG] Start decrypted selected files ...");
  1906. for (tableMetadata* metadata in metadatas) {
  1907. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1908. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDecryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1909. }
  1910. }
  1911. [self tableViewSelect:NO];
  1912. }
  1913. - (void)cmdEncryptedDecryptedFile
  1914. {
  1915. NSString *selector;
  1916. if (_metadata.cryptated == YES) selector = selectorDecryptFile;
  1917. if (_metadata.cryptated == NO) selector = selectorEncryptFile;
  1918. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  1919. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  1920. }
  1921. - (void)encryptedFile:(tableMetadata *)metadata
  1922. {
  1923. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1924. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1925. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1926. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1927. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1928. dispatch_async(dispatch_get_main_queue(), ^{
  1929. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:serverUrl cryptated:YES onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1930. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1931. });
  1932. } else {
  1933. [app messageNotification:@"_encrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1934. }
  1935. }
  1936. - (void)decryptedFile:(tableMetadata *)metadata
  1937. {
  1938. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1939. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1940. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1941. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1942. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1943. dispatch_async(dispatch_get_main_queue(), ^{
  1944. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:serverUrl cryptated:NO onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1945. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1946. });
  1947. } else {
  1948. [app messageNotification:@"_decrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1949. }
  1950. }
  1951. #pragma --------------------------------------------------------------------------------------------
  1952. #pragma mark ===== Progress & Task Button =====
  1953. #pragma --------------------------------------------------------------------------------------------
  1954. - (void)triggerProgressTask:(NSNotification *)notification
  1955. {
  1956. NSDictionary *dict = notification.userInfo;
  1957. NSString *fileID = [dict valueForKey:@"fileID"];
  1958. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1959. BOOL cryptated = [[dict valueForKey:@"cryptated"] boolValue];
  1960. float progress = [[dict valueForKey:@"progress"] floatValue];
  1961. // CCProgress
  1962. if (progress == 0)
  1963. [self.navigationController cancelCCProgress];
  1964. else
  1965. [self.navigationController setCCProgressPercentage:progress*100 andTintColor: [NCBrandColor sharedInstance].navigationBarProgress];
  1966. // Check
  1967. if (!fileID)
  1968. return;
  1969. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1970. if (![serverUrl isEqualToString:_serverUrl])
  1971. return;
  1972. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1973. if (indexPath) {
  1974. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1975. if (cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  1976. else cell.progressView.progressTintColor = [UIColor blackColor];
  1977. cell.progressView.hidden = NO;
  1978. [cell.progressView setProgress:progress];
  1979. }
  1980. }
  1981. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1982. {
  1983. UITouch * touch = [[event allTouches] anyObject];
  1984. CGPoint location = [touch locationInView:self.tableView];
  1985. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  1986. if (indexPath) {
  1987. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1988. if (metadata)
  1989. [self reloadTaskButton:metadata];
  1990. }
  1991. }
  1992. - (void)reloadTaskButton:(tableMetadata *)metadata
  1993. {
  1994. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1995. __block NSURLSessionTask *findTask;
  1996. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1997. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  1998. NSString *fileID = metadata.fileID;
  1999. // DOWNLOAD
  2000. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2001. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2002. for (NSURLSessionUploadTask *task in downloadTasks)
  2003. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2004. findTask = task;
  2005. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  2006. [task cancel];
  2007. }
  2008. if (!findTask) {
  2009. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  2010. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2011. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2012. }
  2013. }];
  2014. }
  2015. // UPLOAD
  2016. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2017. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2018. for (NSURLSessionUploadTask *task in uploadTasks)
  2019. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2020. findTask = task;
  2021. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  2022. [task cancel];
  2023. }
  2024. if (!findTask) {
  2025. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  2026. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2027. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2028. }
  2029. }];
  2030. }
  2031. }
  2032. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  2033. {
  2034. UITouch * touch = [[event allTouches] anyObject];
  2035. CGPoint location = [touch locationInView:self.tableView];
  2036. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2037. if (indexPath) {
  2038. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2039. if (metadata)
  2040. [self cancelTaskButton:metadata reloadTable:YES];
  2041. }
  2042. }
  2043. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  2044. {
  2045. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2046. __block NSURLSessionTask *findTask;
  2047. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2048. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2049. NSString *fileID = metadata.fileID;
  2050. // DOWNLOAD
  2051. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2052. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2053. for (NSURLSessionTask *task in downloadTasks)
  2054. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2055. findTask = task;
  2056. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2057. [task cancel];
  2058. }
  2059. if (!findTask) {
  2060. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2061. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2062. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2063. }
  2064. }];
  2065. }
  2066. // UPLOAD
  2067. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2068. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2069. for (NSURLSessionUploadTask *task in uploadTasks)
  2070. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2071. findTask = task;
  2072. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2073. [task cancel];
  2074. }
  2075. if (!findTask) {
  2076. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2077. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2078. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2079. }
  2080. }];
  2081. }
  2082. }
  2083. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  2084. {
  2085. UITouch * touch = [[event allTouches] anyObject];
  2086. CGPoint location = [touch locationInView:self.tableView];
  2087. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2088. if (indexPath) {
  2089. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2090. if (metadata)
  2091. [self stopTaskButton:metadata];
  2092. }
  2093. }
  2094. - (void)stopTaskButton:(tableMetadata *)metadata
  2095. {
  2096. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2097. __block NSURLSessionTask *findTask;
  2098. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2099. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2100. NSString *fileID = metadata.fileID;
  2101. // UPLOAD
  2102. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2103. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2104. for (NSURLSessionUploadTask *task in uploadTasks)
  2105. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2106. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2107. findTask = task;
  2108. [task cancel];
  2109. }
  2110. if (!findTask) {
  2111. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2112. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2113. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2114. }
  2115. }];
  2116. }
  2117. }
  2118. #pragma --------------------------------------------------------------------------------------------
  2119. #pragma mark ===== Shared =====
  2120. #pragma --------------------------------------------------------------------------------------------
  2121. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  2122. {
  2123. [_hud hideHud];
  2124. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2125. // change account ?
  2126. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  2127. if([record.account isEqualToString:metadataNet.account] == NO)
  2128. return;
  2129. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  2130. if (result) {
  2131. appDelegate.sharesLink = result[0];
  2132. appDelegate.sharesUserAndGroup = result[1];
  2133. }
  2134. // Notify Shares View
  2135. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  2136. if (openWindow) {
  2137. if (_shareOC) {
  2138. [_shareOC reloadData];
  2139. } else {
  2140. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2141. // Apriamo la view
  2142. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  2143. _shareOC.delegate = self;
  2144. _shareOC.metadata = metadata;
  2145. _shareOC.serverUrl = metadataNet.serverUrl;
  2146. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  2147. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  2148. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  2149. [self presentViewController:_shareOC animated:YES completion:nil];
  2150. }
  2151. }
  2152. [self tableViewReloadData];
  2153. }
  2154. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2155. {
  2156. [_hud hideHud];
  2157. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2158. if (_shareOC)
  2159. [_shareOC reloadData];
  2160. [self tableViewReloadData];
  2161. if (errorCode == 401)
  2162. [self changePasswordAccount];
  2163. }
  2164. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  2165. {
  2166. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2167. metadataNet.action = actionShare;
  2168. metadataNet.fileID = metadata.fileID;
  2169. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2170. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2171. metadataNet.password = password;
  2172. metadataNet.selector = selectorShare;
  2173. metadataNet.serverUrl = serverUrl;
  2174. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2175. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2176. }
  2177. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  2178. {
  2179. [_hud hideHud];
  2180. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2181. // rimuoviamo la condivisione da db
  2182. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  2183. if (result) {
  2184. appDelegate.sharesLink = result[0];
  2185. appDelegate.sharesUserAndGroup = result[1];
  2186. }
  2187. if (_shareOC)
  2188. [_shareOC reloadData];
  2189. [self tableViewReloadData];
  2190. }
  2191. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  2192. {
  2193. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2194. metadataNet.action = actionUnShare;
  2195. metadataNet.fileID = metadata.fileID;
  2196. metadataNet.fileName = metadata.fileName;
  2197. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2198. metadataNet.selector = selectorUnshare;
  2199. metadataNet.serverUrl = serverUrl;
  2200. metadataNet.share = share;
  2201. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2202. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2203. }
  2204. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2205. {
  2206. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2207. metadataNet.action = actionUpdateShare;
  2208. metadataNet.fileID = metadata.fileID;
  2209. metadataNet.expirationTime = expirationTime;
  2210. metadataNet.password = password;
  2211. metadataNet.selector = selectorUpdateShare;
  2212. metadataNet.serverUrl = serverUrl;
  2213. metadataNet.share = share;
  2214. metadataNet.sharePermission = permission;
  2215. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2216. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2217. }
  2218. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2219. {
  2220. [_hud hideHud];
  2221. if (_shareOC)
  2222. [_shareOC reloadUserAndGroup:items];
  2223. }
  2224. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2225. {
  2226. [_hud hideHud];
  2227. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2228. }
  2229. - (void)getUserAndGroup:(NSString *)find
  2230. {
  2231. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2232. metadataNet.action = actionGetUserAndGroup;
  2233. metadataNet.options = find;
  2234. metadataNet.selector = selectorGetUserAndGroup;
  2235. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2236. [_hud visibleIndeterminateHud];
  2237. }
  2238. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2239. {
  2240. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2241. metadataNet.action = actionShareWith;
  2242. metadataNet.fileID = metadata.fileID;
  2243. metadataNet.directoryID = directoryID;
  2244. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2245. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2246. metadataNet.serverUrl = serverUrl;
  2247. metadataNet.selector = selectorShare;
  2248. metadataNet.share = user;
  2249. metadataNet.shareeType = shareeType;
  2250. metadataNet.sharePermission = permission;
  2251. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2252. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2253. }
  2254. - (void)openWindowShare:(tableMetadata *)metadata
  2255. {
  2256. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2257. metadataNet.action = actionReadShareServer;
  2258. metadataNet.fileID = metadata.fileID;
  2259. metadataNet.fileName = metadata.fileName;
  2260. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2261. metadataNet.selector = selectorOpenWindowShare;
  2262. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2263. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2264. [_hud visibleIndeterminateHud];
  2265. }
  2266. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2267. {
  2268. CGPoint location = [tapGesture locationInView:self.tableView];
  2269. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2270. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2271. if (metadata)
  2272. [self openWindowShare:metadata];
  2273. }
  2274. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2275. {
  2276. CGPoint location = [tapGesture locationInView:self.tableView];
  2277. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2278. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2279. if (metadata) {
  2280. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2281. vc.metadata = metadata;
  2282. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2283. [self presentViewController:vc animated:YES completion:nil];
  2284. }
  2285. }
  2286. #pragma --------------------------------------------------------------------------------------------
  2287. #pragma mark ===== Favorite =====
  2288. #pragma --------------------------------------------------------------------------------------------
  2289. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2290. {
  2291. _dateReadDataSource = nil;
  2292. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  2293. if (_isSearchMode)
  2294. [self readFolder:metadataNet.serverUrl];
  2295. else
  2296. [self reloadDatasource:metadataNet.serverUrl];
  2297. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2298. if (metadata.directory && metadata.favorite) {
  2299. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileNameData];
  2300. [app.activeFavorites addFavoriteFolder:dir];
  2301. }
  2302. }
  2303. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2304. {
  2305. }
  2306. - (void)addFavorite:(tableMetadata *)metadata
  2307. {
  2308. if (metadata.directory) {
  2309. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2310. } else {
  2311. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2312. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2313. }
  2314. }
  2315. - (void)removeFavorite:(tableMetadata *)metadata
  2316. {
  2317. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2318. }
  2319. #pragma --------------------------------------------------------------------------------------------
  2320. #pragma mark ===== Local =====
  2321. #pragma --------------------------------------------------------------------------------------------
  2322. - (void)addLocal:(tableMetadata *)metadata
  2323. {
  2324. if (metadata.errorPasscode || !metadata.uuid) return;
  2325. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2326. if ([metadata.type isEqualToString: k_metadataType_file])
  2327. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddLocal selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2328. if ([metadata.type isEqualToString: k_metadataType_template]) {
  2329. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileName]];
  2330. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  2331. }
  2332. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2333. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2334. }
  2335. #pragma --------------------------------------------------------------------------------------------
  2336. #pragma mark ===== Open in... =====
  2337. #pragma --------------------------------------------------------------------------------------------
  2338. - (void)openIn:(tableMetadata *)metadata
  2339. {
  2340. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2341. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2342. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2343. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2344. }
  2345. #pragma --------------------------------------------------------------------------------------------
  2346. #pragma mark ===== Remove Local File =====
  2347. #pragma --------------------------------------------------------------------------------------------
  2348. - (void)removeLocalFile:(tableMetadata *)metadata
  2349. {
  2350. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2351. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  2352. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2353. [self reloadDatasource:serverUrl];
  2354. }
  2355. #pragma --------------------------------------------------------------------------------------------
  2356. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2357. #pragma --------------------------------------------------------------------------------------------
  2358. - (void)orderTable:(NSString *)order
  2359. {
  2360. [CCUtility setOrderSettings:order];
  2361. // Clear data-read of DataSource
  2362. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2363. }
  2364. - (void)ascendingTable:(BOOL)ascending
  2365. {
  2366. [CCUtility setAscendingSettings:ascending];
  2367. // Clear data-read of DataSource
  2368. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2369. }
  2370. - (void)directoryOnTop:(BOOL)directoryOnTop
  2371. {
  2372. [CCUtility setDirectoryOnTop:directoryOnTop];
  2373. // Clear data-read of DataSource
  2374. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2375. }
  2376. - (void)tableGroupBy:(NSString *)groupBy
  2377. {
  2378. [CCUtility setGroupBySettings:groupBy];
  2379. // Clear data-read of DataSource
  2380. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2381. }
  2382. #pragma --------------------------------------------------------------------------------------------
  2383. #pragma mark ==== Menu LOGO ====
  2384. #pragma --------------------------------------------------------------------------------------------
  2385. - (void)menuLogo
  2386. {
  2387. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2388. return;
  2389. // Brand
  2390. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2391. return;
  2392. if ([app.netQueue operationCount] > 0 || [app.netQueueDownload operationCount] > 0 || [app.netQueueDownloadWWan operationCount] > 0 || [app.netQueueUpload operationCount] > 0 || [app.netQueueUploadWWan operationCount] > 0 || [[NCManageDatabase sharedInstance] countAutoUploadWithSession:nil] > 0) {
  2393. [app messageNotification:@"_transfers_in_queue_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  2394. return;
  2395. }
  2396. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2397. NSMutableArray *menuArray = [NSMutableArray new];
  2398. for (NSString *account in listAccount) {
  2399. if ([account isEqualToString:app.activeAccount]) continue;
  2400. CCMenuItem *item = [[CCMenuItem alloc] init];
  2401. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2402. item.argument = account;
  2403. item.image = [UIImage imageNamed:@"menuLogoUser"];
  2404. item.target = self;
  2405. item.action = @selector(changeDefaultAccount:);
  2406. [menuArray addObject:item];
  2407. }
  2408. if ([menuArray count] == 0)
  2409. return;
  2410. OptionalConfiguration options;
  2411. Color textColor, backgroundColor;
  2412. textColor.R = 0;
  2413. textColor.G = 0;
  2414. textColor.B = 0;
  2415. backgroundColor.R = 1;
  2416. backgroundColor.G = 1;
  2417. backgroundColor.B = 1;
  2418. NSInteger originY = 60;
  2419. options.arrowSize = 9;
  2420. options.marginXSpacing = 7;
  2421. options.marginYSpacing = 10;
  2422. options.intervalSpacing = 20;
  2423. options.menuCornerRadius = 6.5;
  2424. options.maskToBackground = NO;
  2425. options.shadowOfMenu = YES;
  2426. options.hasSeperatorLine = YES;
  2427. options.seperatorLineHasInsets = YES;
  2428. options.textColor = textColor;
  2429. options.menuBackgroundColor = backgroundColor;
  2430. CGRect rect = self.view.frame;
  2431. rect.origin.y = rect.origin.y + originY;
  2432. rect.size.height = rect.size.height - originY;
  2433. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2434. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2435. }
  2436. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2437. {
  2438. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2439. // STOP, erase all in queue networking
  2440. [app cancelAllOperations];
  2441. [[CCNetworking sharedNetworking] settingSessionsDownload:YES upload:YES taskStatus:k_taskStatusCancel activeAccount:app.activeAccount activeUser:app.activeUser activeUrl:app.activeUrl];
  2442. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2443. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2444. if (tableAccount)
  2445. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password];
  2446. // go to home sweet home
  2447. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil];
  2448. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2449. });
  2450. }
  2451. #pragma --------------------------------------------------------------------------------------------
  2452. #pragma mark ==== ReMenu ====
  2453. #pragma --------------------------------------------------------------------------------------------
  2454. - (void)createReMenuBackgroundView:(REMenu *)menu
  2455. {
  2456. __block CGFloat navigationBarH = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
  2457. _reMenuBackgroundView.frame = CGRectMake(0, navigationBarH, self.view.frame.size.width, self.view.frame.size.height);
  2458. [UIView animateWithDuration:0.2 animations:^{
  2459. float height = (self.view.frame.size.height + navigationBarH) - (menu.menuView.frame.size.height - self.navigationController.navigationBar.frame.size.height + 3);
  2460. if (height < self.tabBarController.tabBar.frame.size.height)
  2461. height = self.tabBarController.tabBar.frame.size.height;
  2462. _reMenuBackgroundView.frame = CGRectMake(0, self.view.frame.size.height + navigationBarH, self.view.frame.size.width, - height);
  2463. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2464. }];
  2465. }
  2466. - (void)createReMainMenu
  2467. {
  2468. NSString *ordinamento;
  2469. NSString *groupBy = _directoryGroupBy;
  2470. __block NSString *nuovoOrdinamento;
  2471. NSString *titoloNuovo, *titoloAttuale;
  2472. BOOL ascendente;
  2473. __block BOOL nuovoAscendente;
  2474. UIImage *image;
  2475. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2476. app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2477. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2478. [self tableViewSelect:YES];
  2479. }
  2480. }];
  2481. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2482. ordinamento = _directoryOrder;
  2483. if ([ordinamento isEqualToString:@"fileName"]) {
  2484. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brand];
  2485. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2486. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2487. nuovoOrdinamento = @"date";
  2488. }
  2489. if ([ordinamento isEqualToString:@"date"]) {
  2490. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brand];
  2491. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2492. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2493. nuovoOrdinamento = @"fileName";
  2494. }
  2495. app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2496. [self orderTable:nuovoOrdinamento];
  2497. }];
  2498. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2499. ascendente = [CCUtility getAscendingSettings];
  2500. if (ascendente) {
  2501. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brand];
  2502. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2503. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2504. nuovoAscendente = false;
  2505. }
  2506. if (!ascendente) {
  2507. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brand];
  2508. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2509. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2510. nuovoAscendente = true;
  2511. }
  2512. app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2513. [self ascendingTable:nuovoAscendente];
  2514. }];
  2515. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2516. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2517. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2518. app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2519. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2520. else [self tableGroupBy:@"alphabetic"];
  2521. }];
  2522. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2523. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2524. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2525. app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2526. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2527. else [self tableGroupBy:@"typefile"];
  2528. }];
  2529. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2530. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2531. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2532. app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2533. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2534. else [self tableGroupBy:@"date"];
  2535. }];
  2536. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2537. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2538. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2539. app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2540. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2541. else [self directoryOnTop:YES];
  2542. }];
  2543. // REMENU --------------------------------------------------------------------------------------------------------------
  2544. app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2545. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2546. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2547. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2548. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2549. app.reMainMenu.separatorHeight = 0.5;
  2550. app.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2551. app.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2552. app.reMainMenu.textColor = [UIColor blackColor];
  2553. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2554. app.reMainMenu.textShadowColor = nil;
  2555. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2556. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2557. app.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2558. app.reMainMenu.highlightedSeparatorColor = nil;
  2559. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2560. app.reMainMenu.highlightedTextShadowColor = nil;
  2561. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2562. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2563. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2564. app.reMainMenu.subtitleTextShadowColor = nil;
  2565. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2566. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2567. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2568. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2569. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2570. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2571. app.reMainMenu.borderWidth = 0.3;
  2572. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2573. app.reMainMenu.animationDuration = 0.2;
  2574. app.reMainMenu.closeAnimationDuration = 0.2;
  2575. app.reMainMenu.bounce = NO;
  2576. [app.reMainMenu setClosePreparationBlock:^{
  2577. // Backgroun reMenu (Gesture)
  2578. [_reMenuBackgroundView removeFromSuperview];
  2579. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2580. }];
  2581. }
  2582. - (void)toggleReMainMenu
  2583. {
  2584. if (app.reMainMenu.isOpen) {
  2585. [app.reMainMenu close];
  2586. } else {
  2587. [self createReMainMenu];
  2588. [app.reMainMenu showFromNavigationController:self.navigationController];
  2589. // Backgroun reMenu & (Gesture)
  2590. [self createReMenuBackgroundView:app.reMainMenu];
  2591. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2592. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2593. }
  2594. }
  2595. - (void)createReSelectMenu
  2596. {
  2597. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2598. app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"deleteSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2599. [self deleteFile];
  2600. }];
  2601. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2602. app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"moveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2603. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2604. }];
  2605. if (app.isCryptoCloudMode) {
  2606. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2607. app.encryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"encryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2608. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2609. }];
  2610. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2611. app.decryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"decryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2612. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2613. }];
  2614. }
  2615. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2616. app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_folders_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"downloadSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2617. [self downloadSelectedFilesFolders];
  2618. }];
  2619. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2620. app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"saveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2621. [self saveSelectedFiles];
  2622. }];
  2623. // REMENU --------------------------------------------------------------------------------------------------------------
  2624. if (app.isCryptoCloudMode) {
  2625. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2626. } else {
  2627. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2628. }
  2629. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2630. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2631. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2632. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2633. app.reSelectMenu.separatorHeight = 0.5;
  2634. app.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2635. app.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2636. app.reSelectMenu.textColor = [UIColor blackColor];
  2637. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2638. app.reSelectMenu.textShadowColor = nil;
  2639. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2640. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2641. app.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2642. app.reSelectMenu.highlightedSeparatorColor = nil;
  2643. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2644. app.reSelectMenu.highlightedTextShadowColor = nil;
  2645. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2646. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2647. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2648. app.reSelectMenu.subtitleTextShadowColor = nil;
  2649. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2650. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2651. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2652. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2653. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2654. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2655. app.reSelectMenu.borderWidth = 0.3;
  2656. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2657. app.reSelectMenu.closeAnimationDuration = 0.2;
  2658. app.reSelectMenu.animationDuration = 0.2;
  2659. app.reSelectMenu.bounce = NO;
  2660. [app.reSelectMenu setClosePreparationBlock:^{
  2661. // Backgroun reMenu (Gesture)
  2662. [_reMenuBackgroundView removeFromSuperview];
  2663. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2664. }];
  2665. }
  2666. - (void)toggleReSelectMenu
  2667. {
  2668. if (app.reSelectMenu.isOpen) {
  2669. [app.reSelectMenu close];
  2670. } else {
  2671. [self createReSelectMenu];
  2672. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2673. // Backgroun reMenu & (Gesture)
  2674. [self createReMenuBackgroundView:app.reSelectMenu];
  2675. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2676. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2677. }
  2678. }
  2679. #pragma --------------------------------------------------------------------------------------------
  2680. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2681. #pragma --------------------------------------------------------------------------------------------
  2682. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2683. {
  2684. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2685. UITableView *tableView = (UITableView*)self.view;
  2686. CGPoint touchPoint = [recognizer locationInView:self.view];
  2687. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2688. if (indexPath)
  2689. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2690. else
  2691. _metadata = nil;
  2692. [self becomeFirstResponder];
  2693. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2694. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2695. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2696. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2697. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2698. UIMenuItem *pasteFileEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_encrypted_", nil) action:@selector(pasteFileEncrypted:)];
  2699. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2700. UIMenuItem *pasteFilesEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_encrypted_", nil) action:@selector(pasteFilesEncrypted:)];
  2701. if (app.isCryptoCloudMode)
  2702. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, pasteFileEncryptedItem, pasteFilesEncryptedItem, nil]];
  2703. else
  2704. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2705. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2706. [menuController setMenuVisible:YES animated:YES];
  2707. }
  2708. }
  2709. - (BOOL)canBecomeFirstResponder
  2710. {
  2711. return YES;
  2712. }
  2713. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2714. {
  2715. // For copy file, copy files, Open in ... :
  2716. //
  2717. // NO Directory
  2718. // NO Error Passcode
  2719. // NO In Session mode (download/upload)
  2720. // NO Template
  2721. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2722. if (_isSelectedMode == NO && _metadata && !_metadata.directory && !_metadata.errorPasscode && [_metadata.session length] == 0 && ![_metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2723. // NO Cryptated with Title lenght = 0
  2724. if (!_metadata.cryptated || (_metadata.cryptated && _metadata.title.length > 0))
  2725. return YES;
  2726. }
  2727. return NO;
  2728. }
  2729. if (@selector(copyFiles:) == action) {
  2730. if (_isSelectedMode) {
  2731. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2732. for (tableMetadata *metadata in selectedMetadatas) {
  2733. if (!metadata.directory && !metadata.errorPasscode && metadata.session.length == 0 && ![metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2734. // NO Cryptated with Title lenght = 0
  2735. if (!metadata.cryptated || (metadata.cryptated && metadata.title.length > 0))
  2736. return YES;
  2737. }
  2738. }
  2739. }
  2740. return NO;
  2741. }
  2742. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2743. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2744. NSArray *items = [pasteboard items];
  2745. if ([items count] == 1) {
  2746. // Value : (NSData) fileID
  2747. NSDictionary *dic = [items objectAtIndex:0];
  2748. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2749. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2750. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2751. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2752. if (directoryUser) {
  2753. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2754. return YES;
  2755. }
  2756. return NO;
  2757. } else return NO;
  2758. }
  2759. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2760. BOOL isValid = NO;
  2761. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2762. NSArray *items = [pasteboard items];
  2763. if ([items count] <= 1) return NO;
  2764. for (NSDictionary *dic in items) {
  2765. // Value : (NSData) fileID
  2766. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2767. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2768. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2769. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2770. if (directoryUser) {
  2771. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2772. isValid = YES;
  2773. }
  2774. }
  2775. return isValid;
  2776. }
  2777. return NO;
  2778. }
  2779. /************************************ COPY ************************************/
  2780. - (void)copyFile:(id)sender
  2781. {
  2782. // Remove all item
  2783. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2784. pasteboard.items = [[NSArray alloc] init];
  2785. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2786. [self copyFileToPasteboard:_metadata];
  2787. } else {
  2788. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2789. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2790. }
  2791. }
  2792. - (void)copyFiles:(id)sender
  2793. {
  2794. // Remove all item
  2795. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2796. pasteboard.items = [[NSArray alloc] init];
  2797. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2798. for (tableMetadata *metadata in selectedMetadatas) {
  2799. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2800. [self copyFileToPasteboard:metadata];
  2801. } else {
  2802. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2803. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2804. }
  2805. }
  2806. [self tableViewSelect:NO];
  2807. }
  2808. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2809. {
  2810. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2811. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2812. // Value : (NSData) fileID
  2813. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2814. [items addObject:item];
  2815. [pasteboard setItems:items];
  2816. }
  2817. /************************************ OPEN IN ... ************************************/
  2818. - (void)openinFile:(id)sender
  2819. {
  2820. [self openIn:_metadata];
  2821. }
  2822. /************************************ PASTE ************************************/
  2823. - (void)pasteFile:(id)sender
  2824. {
  2825. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2826. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2827. }
  2828. - (void)pasteFileEncrypted:(id)sender
  2829. {
  2830. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2831. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2832. }
  2833. - (void)pasteFiles:(id)sender
  2834. {
  2835. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2836. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2837. }
  2838. - (void)pasteFilesEncrypted:(id)sender
  2839. {
  2840. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2841. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2842. }
  2843. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2844. {
  2845. for (NSDictionary *dic in items) {
  2846. // Value : (NSData) fileID
  2847. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2848. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2849. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2850. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2851. if (!metadata || !account) return;
  2852. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2853. if (directoryUser) {
  2854. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2855. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint]];
  2856. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:_serverUrl cryptated:cryptated onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  2857. }
  2858. }
  2859. }
  2860. }
  2861. #pragma --------------------------------------------------------------------------------------------
  2862. #pragma mark ===== Lock Passcode =====
  2863. #pragma --------------------------------------------------------------------------------------------
  2864. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2865. {
  2866. return _failedAttempts;
  2867. }
  2868. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2869. {
  2870. return _lockUntilDate;
  2871. }
  2872. - (void)passcodeViewCloseButtonPressed:(id)sender
  2873. {
  2874. [self dismissViewControllerAnimated:YES completion:nil];
  2875. }
  2876. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2877. {
  2878. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2879. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2880. _lockUntilDate = nil;
  2881. _failedAttempts = 0;
  2882. aResultHandler(YES);
  2883. } else aResultHandler(NO);
  2884. } else aResultHandler(YES);
  2885. }
  2886. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2887. {
  2888. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2889. switch (aViewController.type) {
  2890. case BKPasscodeViewControllerCheckPasscodeType: {
  2891. if (aViewController.fromType == CCBKPasscodeFromPasscode) {
  2892. // verifichiamo se il passcode è corretto per il seguente file -> UUID
  2893. if ([[CCCrypto sharedManager] verifyPasscode:aPasscode uuid:_metadata.uuid text:_metadata.title]) {
  2894. // scriviamo il passcode
  2895. [CCUtility setKeyChainPasscodeForUUID:_metadata.uuid conPasscode:aPasscode];
  2896. [self readFolder:_serverUrl];
  2897. } else {
  2898. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2899. [alertView show];
  2900. }
  2901. }
  2902. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2903. // possiamo procedere alla prossima directory
  2904. [self performSegueDirectoryWithControlPasscode:false];
  2905. // avviamo la sessione Passcode Lock con now
  2906. app.sessionePasscodeLock = [NSDate date];
  2907. }
  2908. // disattivazione lock cartella
  2909. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2910. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2911. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2912. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2913. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2914. }
  2915. [self tableViewReloadData];
  2916. }
  2917. }
  2918. break;
  2919. default:
  2920. break;
  2921. }
  2922. }
  2923. - (void)comandoLockPassword
  2924. {
  2925. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2926. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2927. // se non è abilitato il Lock Passcode esci
  2928. if ([[CCUtility getBlockCode] length] == 0) {
  2929. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2930. [alertView show];
  2931. return;
  2932. }
  2933. // se è richiesta la disattivazione si chiede la password
  2934. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  2935. if (directory.lock) {
  2936. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2937. viewController.delegate = self;
  2938. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2939. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2940. viewController.inputViewTitlePassword = YES;
  2941. if ([CCUtility getSimplyBlockCode]) {
  2942. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2943. viewController.passcodeInputView.maximumLength = 6;
  2944. } else {
  2945. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2946. viewController.passcodeInputView.maximumLength = 64;
  2947. }
  2948. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2949. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2950. viewController.touchIDManager = touchIDManager;
  2951. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2952. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2953. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  2954. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2955. [self presentViewController:navigationController animated:YES completion:nil];
  2956. return;
  2957. }
  2958. // ---------------- ACTIVATE PASSWORD
  2959. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2960. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2961. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2962. } else {
  2963. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2964. }
  2965. }
  2966. #pragma mark -
  2967. #pragma --------------------------------------------------------------------------------------------
  2968. #pragma mark ===== Swipe Tablet -> menu =====
  2969. #pragma --------------------------------------------------------------------------------------------
  2970. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  2971. {
  2972. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2973. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2974. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2975. return NO;
  2976. if (metadata == nil || metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0)
  2977. return NO;
  2978. return YES;
  2979. }
  2980. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  2981. {
  2982. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2983. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2984. if (direction == MGSwipeDirectionRightToLeft) {
  2985. // Delete
  2986. if (index == 0)
  2987. [self swipeDelete:indexPath];
  2988. // More
  2989. if (index == 1)
  2990. [self swipeMore:indexPath];
  2991. //dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2992. //});
  2993. }
  2994. if (direction == MGSwipeDirectionLeftToRight) {
  2995. if (_metadata.favorite)
  2996. [self removeFavorite:_metadata];
  2997. else
  2998. [self addFavorite:_metadata];
  2999. }
  3000. return YES;
  3001. }
  3002. - (void)swipeDelete:(NSIndexPath *)indexPath
  3003. {
  3004. // Directory locked ?
  3005. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID] addFileName:_metadata.fileNameData];
  3006. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  3007. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) {
  3008. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  3009. return;
  3010. }
  3011. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  3012. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  3013. [self performSelector:@selector(deleteFile) withObject:nil];
  3014. }]];
  3015. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3016. [alertController dismissViewControllerAnimated:YES completion:nil];
  3017. }]];
  3018. alertController.popoverPresentationController.sourceView = self.view;
  3019. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  3020. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3021. [alertController.view layoutIfNeeded];
  3022. [self presentViewController:alertController animated:YES completion:nil];
  3023. }
  3024. - (void)swipeMore:(NSIndexPath *)indexPath
  3025. {
  3026. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3027. NSString *titoloCriptaDecripta, *titoloLock, *titleFavorite;
  3028. if (_metadata.cryptated) titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_decrypt_", nil)];
  3029. else titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  3030. if (_metadata.favorite) {
  3031. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  3032. } else {
  3033. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  3034. }
  3035. if (_metadata.directory) {
  3036. // calcolo lockServerUrl
  3037. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3038. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  3039. if (directory.lock)
  3040. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  3041. else
  3042. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  3043. }
  3044. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", _metadata.fileID]];
  3045. // ******************************************* AHKActionSheet *******************************************
  3046. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.view title:nil];
  3047. actionSheet.animationDuration = 0.2;
  3048. actionSheet.blurRadius = 0.0f;
  3049. actionSheet.blurTintColor = [UIColor colorWithWhite:0.0f alpha:0.50f];
  3050. actionSheet.buttonHeight = 50.0;
  3051. actionSheet.cancelButtonHeight = 50.0f;
  3052. actionSheet.separatorHeight = 5.0f;
  3053. actionSheet.automaticallyTintButtonImages = @(NO);
  3054. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].cryptocloud };
  3055. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3056. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].brand };
  3057. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3058. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  3059. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  3060. // ******************************************* DIRECTORY *******************************************
  3061. if (_metadata.directory) {
  3062. BOOL lockDirectory = NO;
  3063. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3064. // Directory bloccata ?
  3065. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, dirServerUrl]];
  3066. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3067. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  3068. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  3069. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3070. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:_metadata.iconName] color:[NCBrandColor sharedInstance].brand]
  3071. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3072. height: 50.0
  3073. type: AHKActionSheetButtonTypeDisabled
  3074. handler: nil
  3075. ];
  3076. if (_metadata.cryptated == NO && !lockDirectory) {
  3077. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3078. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3079. backgroundColor:[UIColor whiteColor]
  3080. height: 50.0
  3081. type:AHKActionSheetButtonTypeDefault
  3082. handler:^(AHKActionSheet *as) {
  3083. [self openWindowShare:_metadata];
  3084. }];
  3085. }
  3086. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  3087. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3088. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3089. backgroundColor:[UIColor whiteColor]
  3090. height: 50.0
  3091. type:AHKActionSheetButtonTypeDefault
  3092. handler:^(AHKActionSheet *as) {
  3093. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3094. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3095. textField.text = _metadata.fileNamePrint;
  3096. //textField.selectedTextRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:textField.endOfDocument];
  3097. //textField.delegate = self;
  3098. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3099. }];
  3100. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3101. NSLog(@"Cancel action");
  3102. }];
  3103. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3104. UITextField *fileName = alertController.textFields.firstObject;
  3105. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3106. }];
  3107. okAction.enabled = NO;
  3108. [alertController addAction:cancelAction];
  3109. [alertController addAction:okAction];
  3110. [self presentViewController:alertController animated:YES completion:nil];
  3111. }];
  3112. }
  3113. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  3114. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3115. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3116. backgroundColor:[UIColor whiteColor]
  3117. height: 50.0
  3118. type:AHKActionSheetButtonTypeDefault
  3119. handler:^(AHKActionSheet *as) {
  3120. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3121. }];
  3122. }
  3123. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && _metadata.cryptated == NO) {
  3124. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  3125. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brand]
  3126. backgroundColor:[UIColor whiteColor]
  3127. height: 50.0
  3128. type:AHKActionSheetButtonTypeDefault
  3129. handler:^(AHKActionSheet *as) {
  3130. // Settings new folder Automatatic upload
  3131. NSString *oldAutoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  3132. [[NCManageDatabase sharedInstance] setAccountAutoUploadFileName:_metadata.fileName];
  3133. [[NCManageDatabase sharedInstance] setAccountAutoUploadDirectory:serverUrl activeUrl:app.activeUrl];
  3134. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:oldAutoUploadDirectory directoryID:nil];
  3135. if (app.activeAccount.length > 0 && app.activePhotos)
  3136. [app.activePhotos reloadDatasourceForced];
  3137. [self readFolder:serverUrl];
  3138. NSLog(@"[LOG] Update Folder Photo");
  3139. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  3140. if ([autoUploadPath length] > 0)
  3141. [[CCSynchronize sharedSynchronize] synchronizedFolder:autoUploadPath selector:selectorReadFolder];
  3142. }];
  3143. }
  3144. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES)) {
  3145. [actionSheet addButtonWithTitle:titoloLock
  3146. image:[UIImage imageNamed:@"actionSheetLock"]
  3147. backgroundColor:[UIColor whiteColor]
  3148. height: 50.0
  3149. type:AHKActionSheetButtonTypeEncrypted
  3150. handler:^(AHKActionSheet *as) {
  3151. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  3152. }];
  3153. }
  3154. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory && app.isCryptoCloudMode) {
  3155. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3156. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3157. backgroundColor:[UIColor whiteColor]
  3158. height: 50.0
  3159. type:AHKActionSheetButtonTypeEncrypted
  3160. handler:^(AHKActionSheet *as) {
  3161. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil];
  3162. }];
  3163. }
  3164. [actionSheet show];
  3165. }
  3166. // ******************************************* FILE *******************************************
  3167. if ([_metadata.type isEqualToString: k_metadataType_file] && !_metadata.directory) {
  3168. UIImage *iconHeader;
  3169. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3170. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  3171. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  3172. else
  3173. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3174. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3175. image: iconHeader
  3176. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3177. height: 50.0
  3178. type: AHKActionSheetButtonTypeDisabled
  3179. handler: nil
  3180. ];
  3181. if (_metadata.cryptated == NO) {
  3182. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3183. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3184. backgroundColor:[UIColor whiteColor]
  3185. height: 50.0
  3186. type:AHKActionSheetButtonTypeDefault
  3187. handler:^(AHKActionSheet *as) {
  3188. [self openWindowShare:_metadata];
  3189. }];
  3190. }
  3191. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3192. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brand]
  3193. backgroundColor:[UIColor whiteColor]
  3194. height: 50.0
  3195. type:AHKActionSheetButtonTypeDefault
  3196. handler:^(AHKActionSheet *as) {
  3197. [self performSelector:@selector(openIn:) withObject:_metadata];
  3198. }];
  3199. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3200. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3201. backgroundColor:[UIColor whiteColor]
  3202. height: 50.0
  3203. type:AHKActionSheetButtonTypeDefault
  3204. handler:^(AHKActionSheet *as) {
  3205. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3206. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3207. //textField.placeholder = _metadata.fileNamePrint;
  3208. textField.text = _metadata.fileNamePrint;
  3209. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3210. }];
  3211. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3212. NSLog(@"Cancel action");
  3213. }];
  3214. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3215. UITextField *fileName = alertController.textFields.firstObject;
  3216. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3217. }];
  3218. okAction.enabled = NO;
  3219. [alertController addAction:cancelAction];
  3220. [alertController addAction:okAction];
  3221. [self presentViewController:alertController animated:YES completion:nil];
  3222. }];
  3223. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3224. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3225. backgroundColor:[UIColor whiteColor]
  3226. height: 50.0
  3227. type:AHKActionSheetButtonTypeDefault
  3228. handler:^(AHKActionSheet *as) {
  3229. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3230. }];
  3231. if (localFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3232. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3233. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brand]
  3234. backgroundColor:[UIColor whiteColor]
  3235. height: 50.0
  3236. type:AHKActionSheetButtonTypeDefault
  3237. handler:^(AHKActionSheet *as) {
  3238. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3239. }];
  3240. }
  3241. if (app.isCryptoCloudMode) {
  3242. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3243. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3244. backgroundColor:[UIColor whiteColor]
  3245. height: 50.0
  3246. type:AHKActionSheetButtonTypeEncrypted
  3247. handler:^(AHKActionSheet *as) {
  3248. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3249. }];
  3250. }
  3251. #ifdef DEBUG
  3252. /*
  3253. [actionSheet addButtonWithTitle:@"Hide file"
  3254. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"admin"] color:[NCBrandColor sharedInstance].brand]
  3255. backgroundColor:[UIColor whiteColor]
  3256. height: 50.0
  3257. type:AHKActionSheetButtonTypeDefault
  3258. handler:^(AHKActionSheet *as) {
  3259. [[NCManageDatabase sharedInstance] setMetadataStatusWithFileID:_metadata.fileID status:k_metadataStatusHide];
  3260. [self reloadDatasource];
  3261. }];
  3262. */
  3263. #endif
  3264. [actionSheet show];
  3265. }
  3266. // ******************************************* TEMPLATE *******************************************
  3267. if ([_metadata.type isEqualToString: k_metadataType_template]) {
  3268. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3269. image: [UIImage imageNamed:_metadata.iconName]
  3270. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3271. height: 50.0
  3272. type: AHKActionSheetButtonTypeDisabled
  3273. handler: nil
  3274. ];
  3275. if ([_metadata.model isEqualToString:@"note"]) {
  3276. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3277. image:[UIImage imageNamed:@"actionSheetRename"]
  3278. backgroundColor:[UIColor whiteColor]
  3279. height: 50.0
  3280. type:AHKActionSheetButtonTypeDefault
  3281. handler:^(AHKActionSheet *as) {
  3282. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3283. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3284. textField.placeholder = _metadata.fileNamePrint;
  3285. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3286. }];
  3287. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3288. NSLog(@"Cancel action");
  3289. }];
  3290. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3291. UITextField *fileName = alertController.textFields.firstObject;
  3292. [self performSelectorOnMainThread:@selector(renameNote:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3293. }];
  3294. okAction.enabled = NO;
  3295. [alertController addAction:cancelAction];
  3296. [alertController addAction:okAction];
  3297. [self presentViewController:alertController animated:YES completion:nil];
  3298. }];
  3299. }
  3300. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3301. image:[UIImage imageNamed:@"actionSheetMove"]
  3302. backgroundColor:[UIColor whiteColor]
  3303. height: 50.0
  3304. type:AHKActionSheetButtonTypeDefault
  3305. handler:^(AHKActionSheet *as) {
  3306. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3307. }];
  3308. [actionSheet show];
  3309. }
  3310. }
  3311. #pragma --------------------------------------------------------------------------------------------
  3312. #pragma mark - ==== Datasource ====
  3313. #pragma --------------------------------------------------------------------------------------------
  3314. - (void)clearDateReadDataSource:(NSNotification *)notification
  3315. {
  3316. _dateReadDataSource = Nil;
  3317. [self reloadDatasource];
  3318. }
  3319. - (void)reloadDatasource
  3320. {
  3321. [self reloadDatasource:_serverUrl];
  3322. }
  3323. - (void)reloadDatasource:(NSString *)serverUrl
  3324. {
  3325. // test
  3326. if (app.activeAccount.length == 0 || serverUrl.length == 0)
  3327. return;
  3328. // Search Mode
  3329. if(_isSearchMode) {
  3330. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3331. [self tableViewReloadData];
  3332. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3333. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3334. _noFilesSearchDescription = @"";
  3335. }
  3336. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3337. _noFilesSearchTitle = @"";
  3338. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3339. }
  3340. [self.tableView reloadEmptyDataSet];
  3341. return;
  3342. }
  3343. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3344. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3345. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3346. if (main) {
  3347. [main reloadDatasource];
  3348. } else {
  3349. [self tableViewReloadData];
  3350. [app.activeTransfers reloadDatasource];
  3351. }
  3352. return;
  3353. }
  3354. [app.activeTransfers reloadDatasource];
  3355. // Settaggio variabili per le ottimizzazioni
  3356. _directoryGroupBy = [CCUtility getGroupBySettings];
  3357. _directoryOrder = [CCUtility getOrderSettings];
  3358. // Controllo data lettura Data Source
  3359. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, serverUrl]];
  3360. NSDate *dateDateRecordDirectory = directory.dateReadDirectory;
  3361. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3362. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3363. _dateReadDataSource = [NSDate date];
  3364. // Data Source
  3365. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND status = %i", app.activeAccount, [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl], k_metadataStatusNormal] sorted:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings]];
  3366. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3367. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3368. } else {
  3369. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3370. }
  3371. [self tableViewReloadData];
  3372. }
  3373. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3374. {
  3375. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3376. if (selectedRows.count > 0) {
  3377. for (NSIndexPath *selectionIndex in selectedRows) {
  3378. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3379. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3380. [metadatas addObject:metadata];
  3381. }
  3382. }
  3383. return metadatas;
  3384. }
  3385. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3386. {
  3387. NSInteger section = indexPath.section + 1;
  3388. NSInteger row = indexPath.row + 1;
  3389. NSInteger totSections =[_sectionDataSource.sections count] ;
  3390. if ((totSections < section) || (section > totSections)) {
  3391. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3392. return nil;
  3393. }
  3394. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3395. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3396. if (fileIDs) {
  3397. NSInteger totRows =[fileIDs count] ;
  3398. if ((totRows < row) || (row > totRows)) {
  3399. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3400. return nil;
  3401. }
  3402. } else {
  3403. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3404. return nil;
  3405. }
  3406. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3407. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3408. return metadata;
  3409. }
  3410. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3411. {
  3412. NSInteger totSections =[_sectionDataSource.sections count] ;
  3413. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3414. #if DEBUG
  3415. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:[NSString stringWithFormat:@"DEBUG [3] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section] delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3416. [alertView show];
  3417. #endif
  3418. return nil;
  3419. }
  3420. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3421. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3422. }
  3423. #pragma --------------------------------------------------------------------------------------------
  3424. #pragma mark - ==== Table ====
  3425. #pragma --------------------------------------------------------------------------------------------
  3426. - (void)tableViewSelect:(BOOL)edit
  3427. {
  3428. // chiudiamo eventuali swipe aperti
  3429. if (edit)
  3430. [self.tableView setEditing:NO animated:NO];
  3431. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3432. [self.tableView setEditing:edit animated:YES];
  3433. _isSelectedMode = edit;
  3434. if (edit)
  3435. [self setUINavigationBarSelected];
  3436. else
  3437. [self setUINavigationBarDefault];
  3438. [_selectedFileIDsMetadatas removeAllObjects];
  3439. [self setTitle];
  3440. }
  3441. - (void)tableViewReloadData
  3442. {
  3443. // store selected cells before relod
  3444. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3445. //store swipeOffset before relod
  3446. [_statusSwipeCell removeAllObjects];
  3447. for (MGSwipeTableCell *cell in self.tableView.visibleCells) {
  3448. NSIndexPath *path = [self.tableView indexPathForCell:cell];
  3449. [_statusSwipeCell setObject:[NSNumber numberWithDouble:cell.swipeOffset] forKey:[@(path.row) stringValue]];
  3450. }
  3451. // reload table view
  3452. [self.tableView reloadData];
  3453. // selected cells stored
  3454. for (NSIndexPath *path in indexPaths)
  3455. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3456. [self setTableViewFooter];
  3457. if (self.tableView.editing)
  3458. [self setTitle];
  3459. }
  3460. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3461. {
  3462. return 60;
  3463. }
  3464. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3465. {
  3466. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3467. }
  3468. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3469. {
  3470. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3471. }
  3472. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3473. {
  3474. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3475. NSString *sectionTitle = [sections objectAtIndex:section];
  3476. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3477. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3478. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3479. return 20.f;
  3480. }
  3481. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3482. {
  3483. float shift;
  3484. UIVisualEffectView *visualEffectView;
  3485. // Titolo
  3486. NSString *titleSection;
  3487. // Controllo
  3488. if ([_sectionDataSource.sections count] == 0)
  3489. return nil;
  3490. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]]) titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3491. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]]) titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3492. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3493. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3494. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3495. else titleSection = NSLocalizedString(titleSection,nil);
  3496. // Formato titolo
  3497. NSString *currentDevice = [CCUtility currentDevice];
  3498. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3499. visualEffectView = [[UIVisualEffectView alloc] init];
  3500. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3501. } else {
  3502. UIVisualEffect *blurEffect;
  3503. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3504. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3505. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3506. }
  3507. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3508. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3509. shift = - 35;
  3510. else
  3511. shift = - 20;
  3512. } else shift = - 10;
  3513. // Title
  3514. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3515. titleLabel.backgroundColor = [UIColor clearColor];
  3516. titleLabel.textColor = [UIColor blackColor];
  3517. titleLabel.font = [UIFont systemFontOfSize:12];
  3518. titleLabel.textAlignment = NSTextAlignmentLeft;
  3519. titleLabel.text = titleSection;
  3520. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3521. [visualEffectView addSubview:titleLabel];
  3522. // Elements
  3523. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3524. elementLabel.backgroundColor = [UIColor clearColor];
  3525. elementLabel.textColor = [UIColor blackColor];;
  3526. elementLabel.font = [UIFont systemFontOfSize:12];
  3527. elementLabel.textAlignment = NSTextAlignmentRight;
  3528. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3529. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3530. NSUInteger rowsCount = [metadatas count];
  3531. if (rowsCount == 0) return nil;
  3532. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3533. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3534. [visualEffectView addSubview:elementLabel];
  3535. return visualEffectView;
  3536. }
  3537. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3538. {
  3539. return [_sectionDataSource.sections indexOfObject:title];
  3540. }
  3541. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3542. {
  3543. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3544. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3545. else
  3546. return nil;
  3547. }
  3548. /*
  3549. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3550. {
  3551. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3552. }
  3553. }
  3554. */
  3555. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3556. {
  3557. NSString *typeCell;
  3558. NSString *dataFile;
  3559. NSString *lunghezzaFile;
  3560. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3561. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata]) {
  3562. return [tableView dequeueReusableCellWithIdentifier:@"CellMainTransfer"];
  3563. }
  3564. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3565. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3566. else typeCell = @"CellMainTransfer";
  3567. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3568. // variable base
  3569. cell.delegate = self;
  3570. cell.indexPath = indexPath;
  3571. // separator
  3572. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3573. // change color selection
  3574. UIView *selectionColor = [[UIView alloc] init];
  3575. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3576. cell.selectedBackgroundView = selectionColor;
  3577. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3578. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3579. // ----------------------------------------------------------------------------------------------------------
  3580. // DEFAULT
  3581. // ----------------------------------------------------------------------------------------------------------
  3582. cell.file.image = nil;
  3583. cell.status.image = nil;
  3584. cell.favorite.image = nil;
  3585. cell.shared.image = nil;
  3586. cell.local.image = nil;
  3587. cell.labelTitle.enabled = YES;
  3588. cell.labelTitle.text = @"";
  3589. cell.labelInfoFile.enabled = YES;
  3590. cell.labelInfoFile.text = @"";
  3591. cell.progressView.progress = 0.0;
  3592. cell.progressView.hidden = YES;
  3593. cell.cancelTaskButton.hidden = YES;
  3594. cell.reloadTaskButton.hidden = YES;
  3595. cell.stopTaskButton.hidden = YES;
  3596. // Encrypted color
  3597. if (metadata.cryptated) {
  3598. cell.labelTitle.textColor = [NCBrandColor sharedInstance].cryptocloud;
  3599. } else {
  3600. cell.labelTitle.textColor = [UIColor blackColor];
  3601. }
  3602. // ----------------------------------------------------------------------------------------------------------
  3603. // File Name & Folder
  3604. // ----------------------------------------------------------------------------------------------------------
  3605. // nome del file
  3606. cell.labelTitle.text = metadata.fileNamePrint;
  3607. // è una directory
  3608. if (metadata.directory) {
  3609. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3610. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3611. lunghezzaFile = @" ";
  3612. // ----------------------------------------------------------------------------------------------------------
  3613. // Favorite Folder
  3614. // ----------------------------------------------------------------------------------------------------------
  3615. if (metadata.favorite) {
  3616. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3617. }
  3618. } else {
  3619. // File
  3620. dataFile = [CCUtility dateDiff:metadata.date];
  3621. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3622. // Plist ancora da scaricare
  3623. if (metadata.cryptated && [metadata.title length] == 0) {
  3624. dataFile = @" ";
  3625. lunghezzaFile = @" ";
  3626. }
  3627. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  3628. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3629. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3630. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3631. if ([metadata.type isEqualToString: k_metadataType_template] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO)
  3632. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", dataFile];
  3633. if ([metadata.type isEqualToString: k_metadataType_file] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO) {
  3634. if (localFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3635. cell.local.image = [UIImage imageNamed:@"local"];
  3636. else
  3637. cell.local.image = nil;
  3638. //cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ • %@", dataFile, lunghezzaFile];
  3639. //cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ ◦ %@", dataFile, lunghezzaFile];
  3640. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ %@", dataFile, lunghezzaFile];
  3641. }
  3642. // Plist ancora da scaricare
  3643. if ([dataFile isEqualToString:@" "] && [lunghezzaFile isEqualToString:@" "])
  3644. cell.labelInfoFile.text = NSLocalizedString(@"_no_plist_pull_down_",nil);
  3645. cell.accessoryType = UITableViewCellAccessoryNone;
  3646. }
  3647. // ----------------------------------------------------------------------------------------------------------
  3648. // File Image View
  3649. // ----------------------------------------------------------------------------------------------------------
  3650. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3651. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3652. cell.file.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  3653. } else {
  3654. if (metadata.directory)
  3655. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:metadata.iconName] color:[NCBrandColor sharedInstance].brand];
  3656. else
  3657. cell.file.image = [UIImage imageNamed:metadata.iconName];
  3658. if (metadata.thumbnailExists)
  3659. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3660. }
  3661. // ----------------------------------------------------------------------------------------------------------
  3662. // Image Status cyptated & Lock Passcode
  3663. // ----------------------------------------------------------------------------------------------------------
  3664. // File Cyptated
  3665. if (metadata.cryptated && metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_template] == NO) {
  3666. cell.status.image = [UIImage imageNamed:@"lock"];
  3667. }
  3668. // Directory con passcode lock attivato
  3669. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  3670. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  3671. if (metadata.directory && (directory.lock && [[CCUtility getBlockCode] length]))
  3672. cell.status.image = [UIImage imageNamed:@"passcode"];
  3673. // ----------------------------------------------------------------------------------------------------------
  3674. // Favorite
  3675. // ----------------------------------------------------------------------------------------------------------
  3676. if (metadata.favorite) {
  3677. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3678. }
  3679. // ----------------------------------------------------------------------------------------------------------
  3680. // Share
  3681. // ----------------------------------------------------------------------------------------------------------
  3682. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3683. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3684. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3685. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3686. // Aggiungiamo il Tap per le shared
  3687. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3688. if (isShare) {
  3689. if (metadata.directory) {
  3690. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3691. cell.shared.userInteractionEnabled = NO;
  3692. } else {
  3693. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3694. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3695. [tap setNumberOfTapsRequired:1];
  3696. cell.shared.userInteractionEnabled = YES;
  3697. [cell.shared addGestureRecognizer:tap];
  3698. }
  3699. }
  3700. if (isMounted) {
  3701. if (metadata.directory) {
  3702. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brand];
  3703. cell.shared.userInteractionEnabled = NO;
  3704. } else {
  3705. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brand];
  3706. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3707. [tap setNumberOfTapsRequired:1];
  3708. cell.shared.userInteractionEnabled = YES;
  3709. [cell.shared addGestureRecognizer:tap];
  3710. }
  3711. }
  3712. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3713. if (metadata.directory) {
  3714. if ([shareLink length] > 0)
  3715. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brand];
  3716. if ([shareUserAndGroup length] > 0)
  3717. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3718. cell.shared.userInteractionEnabled = NO;
  3719. } else {
  3720. if ([shareLink length] > 0)
  3721. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brand];
  3722. if ([shareUserAndGroup length] > 0)
  3723. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3724. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3725. [tap setNumberOfTapsRequired:1];
  3726. cell.shared.userInteractionEnabled = YES;
  3727. [cell.shared addGestureRecognizer:tap];
  3728. }
  3729. }
  3730. } else {
  3731. cell.shared.userInteractionEnabled = NO;
  3732. }
  3733. // ----------------------------------------------------------------------------------------------------------
  3734. // downloadFile
  3735. // ----------------------------------------------------------------------------------------------------------
  3736. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3737. if (metadata.cryptated) cell.status.image = [UIImage imageNamed:@"statusdownloadcrypto"];
  3738. else cell.status.image = [UIImage imageNamed:@"statusdownload"];
  3739. // sessionTaskIdentifier : RELOAD + STOP
  3740. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3741. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3742. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3743. cell.cancelTaskButton.hidden = NO;
  3744. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3745. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3746. cell.reloadTaskButton.hidden = NO;
  3747. }
  3748. // sessionTaskIdentifierPlist : RELOAD
  3749. if (metadata.sessionTaskIdentifierPlist != k_taskIdentifierDone) {
  3750. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3751. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3752. cell.reloadTaskButton.hidden = NO;
  3753. }
  3754. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3755. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3756. if (progress > 0) {
  3757. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3758. else cell.progressView.progressTintColor = [UIColor blackColor];
  3759. cell.progressView.progress = progress;
  3760. cell.progressView.hidden = NO;
  3761. }
  3762. // ----------------------------------------------------------------------------------------------------------
  3763. // downloadFile Error
  3764. // ----------------------------------------------------------------------------------------------------------
  3765. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3766. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3767. if ([metadata.sessionError length] == 0)
  3768. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3769. else
  3770. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3771. }
  3772. }
  3773. // ----------------------------------------------------------------------------------------------------------
  3774. // uploadFile
  3775. // ----------------------------------------------------------------------------------------------------------
  3776. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3777. if (metadata.cryptated) cell.status.image = [UIImage imageNamed:@"statusuploadcrypto"];
  3778. else cell.status.image = [UIImage imageNamed:@"statusupload"];
  3779. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetaskcrypto"] forState:UIControlStateNormal];
  3780. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3781. cell.cancelTaskButton.hidden = NO;
  3782. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3783. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3784. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3785. if (metadata.cryptated) cell.status.image = [UIImage imageNamed:@"statusstopcrypto"];
  3786. else cell.status.image = [UIImage imageNamed:@"statusstop"];
  3787. cell.reloadTaskButton.hidden = NO;
  3788. cell.stopTaskButton.hidden = YES;
  3789. } else {
  3790. if (metadata.cryptated)[cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3791. else [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3792. cell.stopTaskButton.hidden = NO;
  3793. cell.reloadTaskButton.hidden = YES;
  3794. }
  3795. // se non c'è una preview in bianconero metti l'immagine di default
  3796. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3797. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brand];
  3798. cell.labelTitle.enabled = NO;
  3799. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3800. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3801. if (progress > 0) {
  3802. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3803. else cell.progressView.progressTintColor = [UIColor blackColor];
  3804. cell.progressView.progress = progress;
  3805. cell.progressView.hidden = NO;
  3806. }
  3807. // ----------------------------------------------------------------------------------------------------------
  3808. // uploadFileError
  3809. // ----------------------------------------------------------------------------------------------------------
  3810. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3811. cell.labelTitle.enabled = NO;
  3812. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3813. if ([metadata.sessionError length] == 0)
  3814. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3815. else
  3816. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3817. }
  3818. }
  3819. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3820. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3821. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3822. // ======== MGSwipe ========
  3823. //configure left buttons
  3824. if (metadata.favorite)
  3825. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_unfavorite_", nil)] icon:[UIImage imageNamed:@"swipeUnfavorite"] backgroundColor:[UIColor colorWithRed:242.0/255.0 green:220.0/255.0 blue:132.0/255.0 alpha:1.000]]];
  3826. else
  3827. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_favorite_", nil)] icon:[UIImage imageNamed:@"swipeFavorite"] backgroundColor:[UIColor colorWithRed:242.0/255.0 green:220.0/255.0 blue:132.0/255.0 alpha:1.000]]];
  3828. cell.leftExpansion.buttonIndex = 0;
  3829. cell.leftExpansion.fillOnTrigger = NO;
  3830. //centerIconOverText
  3831. MGSwipeButton *favoriteButton = (MGSwipeButton *)[cell.leftButtons objectAtIndex:0];
  3832. [favoriteButton centerIconOverText];
  3833. //configure right buttons
  3834. cell.rightButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_delete_", nil)] icon:[UIImage imageNamed:@"swipeDelete"] backgroundColor:[UIColor redColor]], [MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_more_", nil)] icon:[UIImage imageNamed:@"swipeMore"] backgroundColor:[UIColor lightGrayColor]]];
  3835. cell.rightSwipeSettings.transition = MGSwipeTransitionBorder;
  3836. //centerIconOverText
  3837. MGSwipeButton *deleteButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:0];
  3838. MGSwipeButton *moreButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:1];
  3839. [deleteButton centerIconOverText];
  3840. [moreButton centerIconOverText];
  3841. //restore swipeOffset after relod
  3842. CGFloat swipeOffset = [[_statusSwipeCell objectForKey:[@(indexPath.row) stringValue]] doubleValue];
  3843. if (swipeOffset < 0) {
  3844. //[cell setSwipeOffset:swipeOffset animated:NO completion:nil];
  3845. [cell showSwipe:MGSwipeDirectionRightToLeft animated:NO];
  3846. } else if (swipeOffset > 0) {
  3847. [cell showSwipe:MGSwipeDirectionLeftToRight animated:NO];
  3848. }
  3849. return cell;
  3850. }
  3851. - (void)setTableViewFooter
  3852. {
  3853. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3854. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3855. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3856. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3857. UIFont *appFont = [UIFont systemFontOfSize:12];
  3858. footerLabel.font = appFont;
  3859. footerLabel.textColor = [UIColor grayColor];
  3860. footerLabel.backgroundColor = [UIColor clearColor];
  3861. footerLabel.textAlignment = NSTextAlignmentCenter;
  3862. NSString *folders;
  3863. NSString *files;
  3864. NSString *footerText;
  3865. if (_sectionDataSource.directories > 1) {
  3866. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3867. } else if (_sectionDataSource.directories == 1){
  3868. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3869. } else {
  3870. folders = @"";
  3871. }
  3872. if (_sectionDataSource.files > 1) {
  3873. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3874. } else if (_sectionDataSource.files == 1){
  3875. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3876. } else {
  3877. files = @"";
  3878. }
  3879. if ([folders isEqualToString:@""]) {
  3880. footerText = files;
  3881. } else if ([files isEqualToString:@""]) {
  3882. footerText = folders;
  3883. } else {
  3884. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3885. }
  3886. footerLabel.text = footerText;
  3887. [footerView addSubview:footerLabel];
  3888. [self.tableView setTableFooterView:footerView];
  3889. }
  3890. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3891. {
  3892. NSString *textMessage;
  3893. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3894. // settiamo il record file.
  3895. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3896. // se non può essere selezionata deseleziona
  3897. if ([cell isEditing] == NO)
  3898. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3899. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3900. if (self.tableView.editing) {
  3901. [_selectedFileIDsMetadatas setObject:_metadata forKey:_metadata.fileID];
  3902. [self setTitle];
  3903. return;
  3904. }
  3905. // test crash
  3906. NSArray *metadatas = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  3907. if (indexPath.row >= [metadatas count]) return;
  3908. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3909. // se è in corso una sessione
  3910. if ([_metadata.session length] > 0) return;
  3911. if (_metadata.errorPasscode) {
  3912. // se UUID è nil lo sta ancora caricando quindi esci
  3913. if (!_metadata.uuid) return;
  3914. // esiste un hint ??
  3915. NSString *hint = [[CCCrypto sharedManager] getHintFromFile:_metadata.fileName isLocal:NO directoryUser:app.directoryUser];
  3916. // qui !! la richiesta della nuova passcode
  3917. if ([_metadata.uuid isEqualToString:[CCUtility getUUID]]) {
  3918. // stesso UUID ... la password è stata modificata !!!!!!
  3919. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_same_device_different_passcode_hint_",nil), hint];
  3920. else textMessage = NSLocalizedString(@"_same_device_different_passcode_", nil);
  3921. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3922. [alertView show];
  3923. } else {
  3924. // UUID diverso.
  3925. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_hint_",nil), _metadata.nameCurrentDevice, hint];
  3926. else textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_",nil), _metadata.nameCurrentDevice];
  3927. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3928. [alertView show];
  3929. }
  3930. // chiediamo la passcode e ricarichiamo tutto.
  3931. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3932. viewController.delegate = self;
  3933. viewController.fromType = CCBKPasscodeFromPasscode;
  3934. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3935. viewController.passcodeInputView.maximumLength = 64;
  3936. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3937. viewController.inputViewTitlePassword = NO;
  3938. viewController.title = [NCBrandOptions sharedInstance].brand;
  3939. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3940. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  3941. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3942. [self presentViewController:navigationController animated:YES completion:nil];
  3943. }
  3944. // modello o plist con il title a 0 allora è andato storto qualcosa ... ricaricalo
  3945. if (_metadata.cryptated && [_metadata.title length] == 0) {
  3946. NSString* selector;
  3947. if ([_metadata.type isEqualToString: k_metadataType_template]) selector = selectorLoadModelView;
  3948. else selector = selectorLoadPlist;
  3949. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3950. return;
  3951. }
  3952. // se il plist è caricato ed è un modello aprilo
  3953. if ([_metadata.type isEqualToString:k_metadataType_template]) [self openModel:_metadata.model isNew:false];
  3954. // file
  3955. if (_metadata.directory == NO && _metadata.errorPasscode == NO && [_metadata.type isEqualToString: k_metadataType_file]) {
  3956. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3957. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3958. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  3959. } else {
  3960. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3961. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3962. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3963. }
  3964. }
  3965. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3966. }
  3967. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3968. {
  3969. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3970. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  3971. [self setTitle];
  3972. }
  3973. #pragma --------------------------------------------------------------------------------------------
  3974. #pragma mark ===== Navigation ====
  3975. #pragma --------------------------------------------------------------------------------------------
  3976. - (BOOL)shouldPerformSegue
  3977. {
  3978. // if background return
  3979. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  3980. if (self.view.window == NO)
  3981. return NO;
  3982. // Collapsed ma siamo già in detail esci
  3983. if (self.splitViewController.isCollapsed)
  3984. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  3985. // Video in esecuzione esci
  3986. if (_detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && _detailViewController.photoBrowser.currentVideoPlayerViewController.view.window) return NO;
  3987. return YES;
  3988. }
  3989. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3990. {
  3991. id viewController = segue.destinationViewController;
  3992. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  3993. tableMetadata *metadata;
  3994. if ([viewController isKindOfClass:[UINavigationController class]]) {
  3995. UINavigationController *nav = viewController;
  3996. _detailViewController = (CCDetail *)nav.topViewController;
  3997. } else {
  3998. _detailViewController = segue.destinationViewController;
  3999. }
  4000. if ([sender isKindOfClass:[tableMetadata class]]) {
  4001. metadata = sender;
  4002. [allRecordsDataSourceImagesVideos addObject:sender];
  4003. } else {
  4004. metadata = _metadata;
  4005. for (NSString *fileID in _sectionDataSource.allEtag) {
  4006. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4007. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  4008. [allRecordsDataSourceImagesVideos addObject:metadata];
  4009. }
  4010. }
  4011. _detailViewController.metadataDetail = metadata;
  4012. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  4013. _detailViewController.dateFilterQuery = nil;
  4014. [_detailViewController setTitle:metadata.fileNamePrint];
  4015. }
  4016. // can i go to next viewcontroller
  4017. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  4018. {
  4019. NSString *nomeDir;
  4020. if(self.tableView.editing == NO && _metadata.errorPasscode == NO){
  4021. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  4022. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  4023. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  4024. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  4025. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  4026. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  4027. viewController.delegate = self;
  4028. viewController.fromType = CCBKPasscodeFromLockDirectory;
  4029. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  4030. viewController.inputViewTitlePassword = YES;
  4031. if ([CCUtility getSimplyBlockCode]) {
  4032. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  4033. viewController.passcodeInputView.maximumLength = 6;
  4034. } else {
  4035. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  4036. viewController.passcodeInputView.maximumLength = 64;
  4037. }
  4038. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  4039. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  4040. viewController.touchIDManager = touchIDManager;
  4041. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  4042. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  4043. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  4044. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  4045. [self presentViewController:navController animated:YES completion:nil];
  4046. return;
  4047. }
  4048. if (_metadata.cryptated) nomeDir = [_metadata.fileName substringToIndex:[_metadata.fileName length]-6];
  4049. else nomeDir = _metadata.fileName;
  4050. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  4051. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  4052. if (viewController.isViewLoaded == false || viewController == nil) {
  4053. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  4054. viewController.isFolderEncrypted = _metadata.cryptated;
  4055. viewController.serverUrl = serverUrlPush;
  4056. viewController.titleMain = _metadata.fileNamePrint;
  4057. viewController.textBackButton = _titleMain;
  4058. // save self
  4059. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  4060. }
  4061. // OFF SearchBar
  4062. [viewController cancelSearchBar];
  4063. [self.navigationController pushViewController:viewController animated:YES];
  4064. }
  4065. }
  4066. @end