CCMain.m 253 KB

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